From 5c09c4e65693320b5f5dac92be4717da5567e98f Mon Sep 17 00:00:00 2001 From: Charlie Mordant Date: Sun, 19 Dec 2021 01:13:42 +0100 Subject: [PATCH 1/5] systematically remove the not before reactive --- .../partials/it_patch_update.partial.java.ejs | 12 +- .../java/package/common/get_all_template.ejs | 34 +- .../java/package/common/patch_template.ejs | 12 +- .../package/common/search_stream_template.ejs | 10 +- .../java/package/common/search_template.ejs | 18 +- .../package/service/EntityService.java.ejs | 4 +- .../service/impl/EntityServiceImpl.java.ejs | 4 +- .../package/web/rest/EntityResource.java.ejs | 126 ++--- .../web/rest/EntityResourceIT.java.ejs | 221 ++++---- generators/server/templates/pom.xml.ejs | 12 +- .../config/LiquibaseConfiguration.java.ejs | 14 +- .../config/LocaleConfiguration.java.ejs | 320 +++++------ .../java/package/domain/Authority.java.ejs | 10 +- .../main/java/package/domain/User.java.ejs | 6 +- .../repository/AuthorityRepository.java.ejs | 6 +- .../repository/UserRepository.java.ejs | 148 ++--- .../DomainUserDetailsService.java.ejs | 2 +- .../package/security/SecurityUtils.java.ejs | 56 +- .../package/security/jwt/JWTFilter.java.ejs | 14 +- .../java/package/service/UserService.java.ejs | 438 +++++++-------- .../package/web/rest/AccountResource.java.ejs | 110 ++-- .../package/web/rest/KafkaResource.java.ejs | 38 +- .../package/web/rest/LogoutResource.java.ejs | 62 +-- .../web/rest/PublicUserResource.java.ejs | 48 +- .../web/rest/UserJWTController.java.ejs | 48 +- .../package/web/rest/UserResource.java.ejs | 119 ++-- .../rest/errors/ExceptionTranslator.java.ejs | 24 +- .../src/main/resources/logback-spring.xml.ejs | 6 +- .../security/SecurityUtilsUnitTest.java.ejs | 219 ++++---- .../security/jwt/JWTFilterTest.java.ejs | 90 +-- .../web/rest/AccountResourceIT.java.ejs | 517 +++++++++--------- .../rest/AccountResourceIT_oauth2.java.ejs | 122 ++--- ...ountResourceIT_skipUserManagement.java.ejs | 64 ++- .../package/web/rest/KafkaResourceIT.java.ejs | 50 +- .../web/rest/LogoutResourceIT.java.ejs | 50 +- .../web/rest/PublicUserResourceIT.java.ejs | 77 ++- .../web/rest/UserJWTControllerIT.java.ejs | 71 ++- .../package/web/rest/UserResourceIT.java.ejs | 215 ++++---- .../errors/ExceptionTranslatorIT.java.ejs | 219 ++++---- 39 files changed, 1802 insertions(+), 1814 deletions(-) diff --git a/generators/entity-server/templates/partials/it_patch_update.partial.java.ejs b/generators/entity-server/templates/partials/it_patch_update.partial.java.ejs index 96e9e98fa65..25ca963a37d 100644 --- a/generators/entity-server/templates/partials/it_patch_update.partial.java.ejs +++ b/generators/entity-server/templates/partials/it_patch_update.partial.java.ejs @@ -37,12 +37,7 @@ partialUpdated<%= persistClass %>.set<%= primaryKey.nameCapitalized %>(<%= persi <%_ } _%> <%_ } _%> -<%_ if (!reactive) { _%> -rest<%= entityClass %>MockMvc.perform(patch(ENTITY_API_URL_ID, partialUpdated<%= asEntity(entityClass) %>.get<%= primaryKey.nameCapitalized %>())<% if (testsNeedCsrf) { %>.with(csrf())<% }%> -.contentType("application/merge-patch+json") -.content(TestUtil.convertObjectToJsonBytes(<%= 'partialUpdated' + persistClass %>))) -.andExpect(status().isOk()); -<%_ } else { _%> +<%_ if (reactive) { _%> webTestClient .patch() .uri(ENTITY_API_URL_ID, partialUpdated<%= asEntity(entityClass) %>.get<%= primaryKey.nameCapitalized %>()) @@ -51,6 +46,11 @@ webTestClient .exchange() .expectStatus() .isOk(); +<%_ } else { _%> +rest<%= entityClass %>MockMvc.perform(patch(ENTITY_API_URL_ID, partialUpdated<%= asEntity(entityClass) %>.get<%= primaryKey.nameCapitalized %>())<% if (testsNeedCsrf) { %>.with(csrf())<% }%> +.contentType("application/merge-patch+json") +.content(TestUtil.convertObjectToJsonBytes(<%= 'partialUpdated' + persistClass %>))) +.andExpect(status().isOk()); <%_ } _%> // Validate the <%= entityClass %> in the database diff --git a/generators/entity-server/templates/src/main/java/package/common/get_all_template.ejs b/generators/entity-server/templates/src/main/java/package/common/get_all_template.ejs index fe80ffdd899..2bdc0dfd978 100644 --- a/generators/entity-server/templates/src/main/java/package/common/get_all_template.ejs +++ b/generators/entity-server/templates/src/main/java/package/common/get_all_template.ejs @@ -56,10 +56,10 @@ _%> return <%= entityInstance %>Service.findAll()<% if (reactive) { %>.collectList()<% } %>; <%_ } else if (dtoMapstruct) { _%> <%= reactive ? 'Flux' : 'List' %><<%= persistClass %>> <%= entityInstancePlural %> = <%= entityInstance %>Repository.<% if (relationshipsContainEagerLoad) { %>findAllWithEagerRelationships<% } else { %>findAll<% } %>(); - <%_ if (!reactive) { _%> - return <%= entityListToDtoListReference %>(<%= entityInstancePlural %>); - <%_ } else { _%> + <%_ if (reactive) { _%> return <%= entityInstancePlural %>.map(<%= entityToDtoReference %>).collectList(); + <%_ } else { _%> + return <%= entityListToDtoListReference %>(<%= entityInstancePlural %>); <%_ } _%> <%_ } else { _%> return <%= entityInstance %>Repository.<% if (relationshipsContainEagerLoad) { %>findAllWithEagerRelationships<% } else { %>findAll<% } %>()<% if (reactive) { %>.collectList()<% } %>; @@ -67,7 +67,18 @@ _%> <%_ } else { _%> public <% if (reactive) { %>Mono>>><% } else { %>ResponseEntity>><% } %> getAll<%= entityClassPlural %>(@org.springdoc.api.annotations.ParameterObject Pageable pageable<% if (reactive) { %>, ServerHttpRequest request<% } %><% if (fieldsContainNoOwnerOneToOne) { %>, @RequestParam(required = false) String filter<% } %><% if (relationshipsContainEagerLoad) { %>, @RequestParam(required = false, defaultValue = "false") boolean eagerload<% } %>) {<%- include('get_all_stream_template', {viaService: viaService}); -%> log.debug("REST request to get a page of <%= entityClassPlural %>"); - <%_ if (!reactive) { _%> + <%_ if (reactive) { _%> + return <%= entityInstance %><%= viaService ? 'Service.countAll' : 'Repository.count' %>().zipWith(<%= entityInstance %><%= viaService ? 'Service.findAll' : 'Repository.findAllBy' %>(pageable)<%= reactiveEntityToDto %>.collectList()) + .map(countWithEntities -> { + return ResponseEntity.ok() + .headers( + PaginationUtil.generatePaginationHttpHeaders( + UriComponentsBuilder.fromHttpRequest(request), + new PageImpl<>(countWithEntities.getT2(), pageable, countWithEntities.getT1()) + ) + ).body(countWithEntities.getT2()); + }); + <%_ } else { _%> <%_ if (relationshipsContainEagerLoad) { _%> Page<<%= instanceType %>> page; if (eagerload) { @@ -75,23 +86,12 @@ _%> } else { page = <%= entityInstance %><%= viaService ? 'Service' : 'Repository' %>.findAll(pageable)<%= reactiveEntityToDto %>; } - HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(<% if (!reactive) { %>ServletUriComponentsBuilder.fromCurrentRequest()<% } else { %>UriComponentsBuilder.fromHttpRequest(request)<% } %>, page); + HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(<% if (reactive) { %>UriComponentsBuilder.fromHttpRequest(request)<% } else { %>ServletUriComponentsBuilder.fromCurrentRequest()<% } %>, page); <%_ } else { _%> Page<<%= instanceType %>> page = <%= entityInstance %><%= viaService ? 'Service' : 'Repository' %>.findAll(pageable)<%= reactiveEntityToDto %>; - HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(<% if (!reactive) { %>ServletUriComponentsBuilder.fromCurrentRequest()<% } else { %>UriComponentsBuilder.fromHttpRequest(request)<% } %>, page); + HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(<% if (reactive) { %>UriComponentsBuilder.fromHttpRequest(request)<% } else { %>ServletUriComponentsBuilder.fromCurrentRequest()<% } %>, page); <%_ } _%> return ResponseEntity.ok().headers(headers).body(page.getContent()); - <%_ } else { _%> - return <%= entityInstance %><%= viaService ? 'Service.countAll' : 'Repository.count' %>().zipWith(<%= entityInstance %><%= viaService ? 'Service.findAll' : 'Repository.findAllBy' %>(pageable)<%= reactiveEntityToDto %>.collectList()) - .map(countWithEntities -> { - return ResponseEntity.ok() - .headers( - PaginationUtil.generatePaginationHttpHeaders( - UriComponentsBuilder.fromHttpRequest(request), - new PageImpl<>(countWithEntities.getT2(), pageable, countWithEntities.getT1()) - ) - ).body(countWithEntities.getT2()); - }); <%_ } _%> <%_ } _%> } diff --git a/generators/entity-server/templates/src/main/java/package/common/patch_template.ejs b/generators/entity-server/templates/src/main/java/package/common/patch_template.ejs index 19dd8cda5de..943d7015b30 100644 --- a/generators/entity-server/templates/src/main/java/package/common/patch_template.ejs +++ b/generators/entity-server/templates/src/main/java/package/common/patch_template.ejs @@ -25,10 +25,10 @@ const returnPrefix = (isService) ? 'return' : returnType + '<' + instanceType + const mapper = entityInstance + 'Mapper'; _%> <%_ if(viaService) { _%> - <%_ if(!reactive) { _%> - Optional<<%= instanceType %>> result = <%= entityInstance %>Service.partialUpdate(<%= instanceName %>); - <%_ } else { _%> + <%_ if(reactive) { _%> Mono<<%= instanceType %>> result = <%= entityInstance %>Service.partialUpdate(<%= instanceName %>); + <%_ } else { _%> + Optional<<%= instanceType %>> result = <%= entityInstance %>Service.partialUpdate(<%= instanceName %>); <%_ } _%> <%_ } else { %> <%- returnPrefix %> <%= entityInstance %>Repository.findById(<%= instanceName %>.get<%= primaryKey.nameCapitalized %>()) @@ -53,10 +53,10 @@ _%> <%_ if (searchEngineElasticsearch) { _%> .<%= mapOrFlatMap %>(saved<%= entityClass %> -> { <%= entityInstance %>SearchRepository.save(saved<%= entityClass %>); - <%_ if(!reactive) { %> - return saved<%= entityClass %>; - <%_ } else { %> + <%_ if(reactive) { %> return Mono.just(saved<%= entityClass %>); + <%_ } else { %> + return saved<%= entityClass %>; <%_ } %> }) <%_ } _%> diff --git a/generators/entity-server/templates/src/main/java/package/common/search_stream_template.ejs b/generators/entity-server/templates/src/main/java/package/common/search_stream_template.ejs index 6108184046b..b06ee5e3ac7 100644 --- a/generators/entity-server/templates/src/main/java/package/common/search_stream_template.ejs +++ b/generators/entity-server/templates/src/main/java/package/common/search_stream_template.ejs @@ -20,7 +20,10 @@ const mapper = entityInstance + 'Mapper'; const entityToDtoReference = mapper + '::' + 'toDto'; %> <%_ if (!viaService) { _%> - <%_ if (!reactive) { _%> + <%_ if (reactive) { _%> + return <%= entityInstance %><% if (searchEngineElasticsearch) { %>Search<% } %>Repository.search(query)<%_ if (dtoMapstruct) { %> + .map(<%= entityToDtoReference %>)<%_ } %><%_ if (fromResource) { _%>.collectList()<%_ } _%>; + <%_ } else { _%> <%_ if (searchEngineElasticsearch) { _%> return StreamSupport .stream(<%= entityInstance %>SearchRepository.search(query).spliterator(), false) @@ -33,10 +36,7 @@ const entityToDtoReference = mapper + '::' + 'toDto'; %> <%_ if (dtoMapstruct || searchEngineElasticsearch) { _%> .collect(Collectors.toList()); <%_ } _%> - <%_ } else { _%> - return <%= entityInstance %><% if (searchEngineElasticsearch) { %>Search<% } %>Repository.search(query)<%_ if (dtoMapstruct) { %> - .map(<%= entityToDtoReference %>)<%_ } %><%_ if (fromResource) { _%>.collectList()<%_ } _%>; - <%_ } _%> + <%_ } _%> <%_ } else { _%> return <%= entityInstance %>Service.search(query)<% if (reactive && fromResource) { %>.collectList()<% } %>; <%_ } _%> diff --git a/generators/entity-server/templates/src/main/java/package/common/search_template.ejs b/generators/entity-server/templates/src/main/java/package/common/search_template.ejs index 90399f98992..1a39b721a7d 100644 --- a/generators/entity-server/templates/src/main/java/package/common/search_template.ejs +++ b/generators/entity-server/templates/src/main/java/package/common/search_template.ejs @@ -29,21 +29,21 @@ if (paginationNo) { %> <% } if (!paginationNo) { %> public <% if (reactive) { %>Mono<<% } %>ResponseEntity<<%= listOrFlux %><<%= instanceType %>>><% if (reactive) { %>><% } %> search<%= entityClassPlural %>(@RequestParam String query, @org.springdoc.api.annotations.ParameterObject Pageable pageable<% if (reactive) { %>, ServerHttpRequest request<% } %>) { log.debug("REST request to search for a page of <%= entityClassPlural %> for query {}", query); - <%_ if (!reactive) { _%> - <%_ if (viaService) { _%> - Page<<%= instanceType %>> page = <%= entityInstance %>Service.search(query, pageable); - <%_ } else { _%> - Page<<%= persistClass %>> page = <%= entityInstance %><% if (searchEngineElasticsearch) { %>Search<% } %>Repository.search(query, pageable); - <%_ } _%> - HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(<% if (!reactive) { %>ServletUriComponentsBuilder.fromCurrentRequest()<% } else { %>UriComponentsBuilder.fromHttpRequest(request)<% } %>, page); - return ResponseEntity.ok().headers(headers).body(<% if (!viaService && dtoMapstruct) { %><%= entityListToDtoListReference %>(<% } %>page.getContent()<% if (!viaService && dtoMapstruct) { %>)<% } %>); - <%_ } else { _%> + <%_ if (reactive) { _%> return <%= entityInstance %><%= viaService ? 'Service.' + (searchEngineElasticsearch ? 'searchCount' : 'countAll') : (searchEngineElasticsearch ? 'Search' : '') + 'Repository.count' %>() .map(total -> new PageImpl<>(new ArrayList<>(), pageable, total)) .map(page -> PaginationUtil.generatePaginationHttpHeaders(UriComponentsBuilder.fromHttpRequest(request), page)) .map(headers -> ResponseEntity.ok().headers(headers).body(<%= entityInstance %><%= viaService ? 'Service' : (searchEngineElasticsearch ? 'Search' : '') + 'Repository' %>.search(query, pageable)<% if (!viaService && dtoMapstruct) { %>.map(<%= entityToDtoReference %>)<% } %>)); + <%_ } else { _%> + <%_ if (viaService) { _%> + Page<<%= instanceType %>> page = <%= entityInstance %>Service.search(query, pageable); + <%_ } else { _%> + Page<<%= persistClass %>> page = <%= entityInstance %><% if (searchEngineElasticsearch) { %>Search<% } %>Repository.search(query, pageable); + <%_ } _%> + HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(<% if (reactive) { %>UriComponentsBuilder.fromHttpRequest(request)<% } else { %>ServletUriComponentsBuilder.fromCurrentRequest()<% } %>, page); + return ResponseEntity.ok().headers(headers).body(<% if (!viaService && dtoMapstruct) { %><%= entityListToDtoListReference %>(<% } %>page.getContent()<% if (!viaService && dtoMapstruct) { %>)<% } %>); <%_ } _%> <% } -%> } diff --git a/generators/entity-server/templates/src/main/java/package/service/EntityService.java.ejs b/generators/entity-server/templates/src/main/java/package/service/EntityService.java.ejs index 53faa4edd94..63de131ab0a 100644 --- a/generators/entity-server/templates/src/main/java/package/service/EntityService.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/service/EntityService.java.ejs @@ -71,7 +71,7 @@ public interface <%= entityClass %>Service { * @param <%= instanceName %> the entity to update partially. * @return the persisted entity. */ -<% if (!reactive) { %>Optional<<% } %><% if (reactive) { %>Mono<<% } %><%= instanceType %>> partialUpdate(<%= instanceType %> <%= instanceName %>); + <% if (reactive) { %>Mono<<% } else { %>Optional<<% } %><%= instanceType %>> partialUpdate(<%= instanceType %> <%= instanceName %>); /** * Get all the <%= entityInstancePlural %>. @@ -79,7 +79,7 @@ public interface <%= entityClass %>Service { * @param pageable the pagination information.<% } %> * @return the list of entities. */ - <% if (!paginationNo) { %><%= pageOrFlux %><<%= instanceType %><% } else { %><%= listOrFlux %><<%= instanceType %><% } %>> findAll(<% if (!paginationNo) { %>Pageable pageable<% } %>); + <% if (paginationNo) { %><%= listOrFlux %><<%= instanceType %><% } else { %><%= pageOrFlux %><<%= instanceType %><% } %>> findAll(<% if (!paginationNo) { %>Pageable pageable<% } %>); <%_ for (const relationship of relationships) { _%> <%_ if (relationship.relationshipOneToOne && !relationship.ownerSide) { _%> /** diff --git a/generators/entity-server/templates/src/main/java/package/service/impl/EntityServiceImpl.java.ejs b/generators/entity-server/templates/src/main/java/package/service/impl/EntityServiceImpl.java.ejs index 97851af0b7e..725c570c335 100644 --- a/generators/entity-server/templates/src/main/java/package/service/impl/EntityServiceImpl.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/service/impl/EntityServiceImpl.java.ejs @@ -126,7 +126,7 @@ public class <%= serviceClassName %><% if (serviceImpl) { %> implements <%= enti <%_ if (serviceImpl) { _%> @Override <%_ } _%> - public <% if (!reactive) { %>Optional<<% } %><% if (reactive) { %>Mono<<% } %><%= instanceType %>> partialUpdate(<%= instanceType %> <%= instanceName %>) { + public <% if (reactive) { %>Mono<<% } else { %>Optional<<% } %><%= instanceType %>> partialUpdate(<%= instanceType %> <%= instanceName %>) { log.debug("Request to partially update <%= entityClass %> : {}", <%= instanceName %>); <%- include('../../common/patch_template', {asEntity, asDto, isService: true, viaService: false}); -%> } @@ -147,7 +147,7 @@ public class <%= serviceClassName %><% if (serviceImpl) { %> implements <%= enti <%_ if (databaseTypeSql) { _%> @Transactional(readOnly = true) <%_ } _%> - public <% if (!paginationNo) { %><%= pageOrFlux %><<%= instanceType %><% } else { %><%= listOrFlux %><<%= instanceType %><% } %>> findAll(<% if (!paginationNo) { %>Pageable pageable<% } %>) { + public <% if (paginationNo) { %><%= listOrFlux %><<%= instanceType %><% } else { %><%= pageOrFlux %><<%= instanceType %><% } %>> findAll(<% if (!paginationNo) { %>Pageable pageable<% } %>) { log.debug("Request to get all <%= entityClassPlural %>"); <%_ if (paginationNo) { _%> return <%= entityInstance %>Repository.<% if (relationshipsContainEagerLoad) { %>findAllWithEagerRelationships<% } else { %>findAll<% } %>()<% if (dtoMapstruct) { %><% if (!reactive) { %>.stream()<% } %> diff --git a/generators/entity-server/templates/src/main/java/package/web/rest/EntityResource.java.ejs b/generators/entity-server/templates/src/main/java/package/web/rest/EntityResource.java.ejs index d0c29b07987..f0f62b9ed8b 100644 --- a/generators/entity-server/templates/src/main/java/package/web/rest/EntityResource.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/web/rest/EntityResource.java.ejs @@ -68,10 +68,10 @@ import org.springframework.http.HttpHeaders; <%_ if (reactive) { _%> import org.springframework.http.server.reactive.ServerHttpRequest; <%_ } _%> - <%_ if (!reactive) { _%> -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; - <%_ } else { _%> + <%_ if (reactive) { _%> import org.springframework.web.util.UriComponentsBuilder; + <%_ } else { _%> +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; <%_ } _%> <%_ } _%> <%_ if (reactive || (!jpaMetamodelFiltering && !paginationNo)) { _%> @@ -170,16 +170,16 @@ public class <%= entityClass %>Resource { } <%_ if (saveUserSnapshot) { _%> <% for (const userRelationship of relationships.filter(rel => rel.otherEntity.builtInUser)) { %> - <%_ if (userRelationship.collection) { _%> - if (<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalizedPlural %>() != null) { - // Save users in case they are new and only exist in gateway - userRepository.saveAll(<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalizedPlural %>()); - } - <%_ } else { _%> - if (<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalized %>() != null) { - // Save user in case it's new and only exists in gateway - userRepository.save(<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalized %>()); - } + <%_ if (userRelationship.collection) { _%> + if (<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalizedPlural %>() != null) { + // Save users in case they are new and only exist in gateway + userRepository.saveAll(<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalizedPlural %>()); + } + <%_ } else { _%> + if (<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalized %>() != null) { + // Save user in case it's new and only exists in gateway + userRepository.save(<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalized %>()); + } <%_ } _%> <% } %> <%_ } _%> @@ -187,20 +187,20 @@ public class <%= entityClass %>Resource { <%= instanceName %>.set<%= field.fieldNameCapitalized %>(UUID.randomUUID()); <%_ } _%> <%- include('/partials/save_template', {asEntity, asDto, viaService: viaService, returnDirectly: false, isUsingMapsId: isUsingMapsId, mapsIdAssoc: mapsIdAssoc, isController: true}); -%> - <%_ if (!reactive) { _%> - return ResponseEntity.created(new URI("/api/<%= entityApiUrl %>/" + result.get<%= primaryKey.nameCapitalized %>())) - .headers(HeaderUtil.createEntityCreationAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, result.get<%= primaryKey.nameCapitalized %>()<% if (primaryKey.type !== 'String') { %>.toString()<% } %>)) - .body(result); - <%_ } else { _%> + <%_ if (reactive) { _%> .map(result -> { try { return ResponseEntity.created(new URI("/api/<%= entityApiUrl %>/" + result.get<%= primaryKey.nameCapitalized %>())) - .headers(HeaderUtil.createEntityCreationAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, result.get<%= primaryKey.nameCapitalized %>()<% if (primaryKey.type !== 'String') { %>.toString()<% } %>)) + .headers(HeaderUtil.createEntityCreationAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, result.get<%= primaryKey.nameCapitalized %>()<% if (!primaryKey.typeString) { %>.toString()<% } %>)) .body(result); } catch (URISyntaxException e) { throw new RuntimeException(e); } }); + <%_ } else { _%> + return ResponseEntity.created(new URI("/api/<%= entityApiUrl %>/" + result.get<%= primaryKey.nameCapitalized %>())) + .headers(HeaderUtil.createEntityCreationAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, result.get<%= primaryKey.nameCapitalized %>()<% if (!primaryKey.typeString) { %>.toString()<% } %>)) + .body(result); <%_ } _%> } @@ -227,44 +227,44 @@ public class <%= entityClass %>Resource { throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid"); } - <%_ if (!reactive) { _%> - if (!<%= entityInstance %>Repository.existsById(<%= primaryKey.name %>)) { - throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound"); - } - <%_ } else { _%> + <%_ if (reactive) { _%> return <%= entityInstance %>Repository.existsById(<%= primaryKey.name %>).flatMap(exists -> { if (!exists) { return Mono.error(new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound")); } + <%_ } else { _%> + if (!<%= entityInstance %>Repository.existsById(<%= primaryKey.name %>)) { + throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound"); + } <%_ } _%> <%_ if (saveUserSnapshot) { _%> <% for (const userRelationship of relationships.filter(rel => rel.otherEntity.builtInUser)) { %> - <%_ if (userRelationship.collection) { _%> - if (<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalizedPlural %>() != null) { - // Save users in case they are new and only exist in gateway - userRepository.saveAll(<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalizedPlural %>()); - } - <%_ } else { _%> - if (<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalized %>() != null) { - // Save user in case it's new and only exists in gateway - userRepository.save(<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalized %>()); - } + <%_ if (userRelationship.collection) { _%> + if (<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalizedPlural %>() != null) { + // Save users in case they are new and only exist in gateway + userRepository.saveAll(<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalizedPlural %>()); + } + <%_ } else { _%> + if (<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalized %>() != null) { + // Save user in case it's new and only exists in gateway + userRepository.save(<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalized %>()); + } <%_ } _%> <% } %> <%_ } _%> <%- include('/partials/save_template', {asEntity, asDto, viaService: viaService, returnDirectly: false, isUsingMapsId: false, mapsIdAssoc: mapsIdAssoc}); -%> - <%_ if (!reactive) { _%> - return ResponseEntity.ok() - .headers(HeaderUtil.createEntityUpdateAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, <%= instanceName %>.get<%= primaryKey.nameCapitalized %>()<% if (primaryKey.type !== 'String') { %>.toString()<% } %>)) - .body(result); - <%_ } else { _%> + <%_ if (reactive) { _%> .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND))) .map(result -> ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, result.get<%= primaryKey.nameCapitalized %>()<% if (primaryKey.type !== 'String') { %>.toString()<% } %>)) .body(result) ); }); + <%_ } else { _%> + return ResponseEntity.ok() + .headers(HeaderUtil.createEntityUpdateAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, <%= instanceName %>.get<%= primaryKey.nameCapitalized %>()<% if (primaryKey.type !== 'String') { %>.toString()<% } %>)) + .body(result); <%_ } _%> } @@ -292,40 +292,35 @@ public class <%= entityClass %>Resource { throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid"); } - <%_ if (!reactive) { _%> - if (!<%= entityInstance %>Repository.existsById(<%= primaryKey.name %>)) { - throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound"); - } - <%_ } else { _%> + <%_ if (reactive) { _%> return <%= entityInstance %>Repository.existsById(<%= primaryKey.name %>).flatMap(exists -> { if (!exists) { return Mono.error(new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound")); } + <%_ } else { _%> + if (!<%= entityInstance %>Repository.existsById(<%= primaryKey.name %>)) { + throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound"); + } <%_ } _%> <%_ if (saveUserSnapshot) { _%> <% for (const userRelationship of relationships.filter(rel => rel.otherEntity.builtInUser)) { %> - <%_ if (userRelationship.collection) { _%> - if (<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalizedPlural %>() != null) { - // Save users in case they are new and only exist in gateway - userRepository.saveAll(<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalizedPlural %>()); - } - <%_ } else { _%> - if (<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalized %>() != null) { - // Save user in case it's new and only exists in gateway - userRepository.save(<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalized %>()); - } + <%_ if (userRelationship.collection) { _%> + if (<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalizedPlural %>() != null) { + // Save users in case they are new and only exist in gateway + userRepository.saveAll(<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalizedPlural %>()); + } + <%_ } else { _%> + if (<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalized %>() != null) { + // Save user in case it's new and only exists in gateway + userRepository.save(<%= instanceName %>.get<%= userRelationship.relationshipNameCapitalized %>()); + } <%_ } _%> <% } %> <%_ } _%> <%- include('../../common/patch_template', {asEntity, asDto, isService: false, viaService: viaService}); -%> - <%_ if (!reactive) { _%> - return ResponseUtil.wrapOrNotFound( - result, - HeaderUtil.createEntityUpdateAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, <%= instanceName %>.get<%= primaryKey.nameCapitalized %>()<% if (primaryKey.type !== 'String') { %>.toString()<% } %>) - ); - <%_ } else { _%> + <%_ if (reactive) { _%> return result .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND))) .map(res -> ResponseEntity.ok() @@ -333,6 +328,11 @@ public class <%= entityClass %>Resource { .body(res) ); }); + <%_ } else { _%> + return ResponseUtil.wrapOrNotFound( + result, + HeaderUtil.createEntityUpdateAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, <%= instanceName %>.get<%= primaryKey.nameCapitalized %>()<% if (primaryKey.type !== 'String') { %>.toString()<% } %>) + ); <%_ } _%> } <%_ } _%> @@ -410,9 +410,7 @@ public class <%= entityClass %>Resource { public <% if (reactive) { %>Mono<<% } %>ResponseEntity<% if (reactive) { %>><% } %> delete<%= entityClass %>(@PathVariable <%= primaryKey.type %> id) { log.debug("REST request to delete <%= entityClass %> : {}", id); <%- include('../../common/delete_template', {viaService: viaService, fromResource: true}); -%> - <%_ if (!reactive) { _%> - return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, id<% if (!primaryKey.fields[0].fieldTypeString) { %>.toString()<% } %>)).build(); - <%_ } else { _%> + <%_ if (reactive) { _%> <%_ if (databaseTypeCouchbase) { _%> .then(Mono.just(ResponseEntity.noContent() .headers(HeaderUtil.createEntityDeletionAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, id<% if (primaryKey.type !== 'String') { %>.toString()<% } %>)).build()) @@ -422,6 +420,8 @@ public class <%= entityClass %>Resource { .headers(HeaderUtil.createEntityDeletionAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, id<% if (primaryKey.type !== 'String') { %>.toString()<% } %>)).build() ); <%_ } _%> + <%_ } else { _%> + return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, id<% if (!primaryKey.fields[0].fieldTypeString) { %>.toString()<% } %>)).build(); <%_ } _%> } <%_ } _%> diff --git a/generators/entity-server/templates/src/test/java/package/web/rest/EntityResourceIT.java.ejs b/generators/entity-server/templates/src/test/java/package/web/rest/EntityResourceIT.java.ejs index 35d00964776..4b39cea3028 100644 --- a/generators/entity-server/templates/src/test/java/package/web/rest/EntityResourceIT.java.ejs +++ b/generators/entity-server/templates/src/test/java/package/web/rest/EntityResourceIT.java.ejs @@ -114,10 +114,10 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; <%_ } _%> import org.springframework.beans.factory.annotation.Autowired; -<%_ if (!reactive) { _%> -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -<%_ } else { _%> +<%_ if (reactive) { _%> import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; +<%_ } else { _%> +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; <%_ } _%> <%_ if (searchEngineElasticsearch && !paginationNo || fieldsContainOwnerManyToMany) { _%> import org.springframework.data.domain.PageImpl; @@ -229,10 +229,10 @@ import <%= entityAbsolutePackage %>.domain.enumeration.<%= field.fieldType %>; <%_ if (cacheProviderRedis || searchEngineElasticsearch || fieldsContainOwnerManyToMany) { _%> @ExtendWith(MockitoExtension.class) <%_ } _%> -<%_ if (!reactive) { _%> -@AutoConfigureMockMvc -<%_ } else { _%> +<%_ if (reactive) { _%> @AutoConfigureWebTestClient(timeout = IntegrationTest.DEFAULT_ENTITY_TIMEOUT) +<%_ } else { _%> +@AutoConfigureMockMvc <%_ } _%> @WithMockUser class <%= entityClass %>ResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassandraTest <% } %>{ @@ -462,14 +462,13 @@ if (field.fieldTypeString || field.blobContentTypeText) { @Autowired private EntityManager em; <%_ } _%> -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> @Autowired - private MockMvc rest<%= entityClass %>MockMvc; + private WebTestClient webTestClient; <%_ } else { _%> - @Autowired - private WebTestClient webTestClient; + private MockMvc rest<%= entityClass %>MockMvc; <%_ } _%> private <%= persistClass %> <%= persistInstance %>; @@ -604,17 +603,17 @@ _%> <%_ if (dtoMapstruct) { _%> <%= dtoClass %> <%= dtoInstance %> = <%= entityInstance %>Mapper.toDto(<%= persistInstance %>); <%_ } _%> - <%_ if (!reactive) { _%> - rest<%= entityClass %>MockMvc.perform(post(ENTITY_API_URL)<% if (testsNeedCsrf) { %>.with(csrf())<% }%> - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))) - .andExpect(status().isCreated()); - <%_ } else { _%> + <%_ if (reactive) { _%> webTestClient.post().uri(ENTITY_API_URL) .contentType(MediaType.APPLICATION_JSON) .bodyValue(TestUtil.convertObjectToJsonBytes(<%= restInstance %>)) .exchange() .expectStatus().isCreated(); + <%_ } else { _%> + rest<%= entityClass %>MockMvc.perform(post(ENTITY_API_URL)<% if (testsNeedCsrf) { %>.with(csrf())<% }%> + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))) + .andExpect(status().isCreated()); <%_ } _%> // Validate the <%= entityClass %> in the database @@ -663,17 +662,17 @@ _%> int databaseSizeBeforeCreate = <%= entityInstance %>Repository.findAll()<%= callListBlock %>.size(); // An entity with an existing ID cannot be created, so this API call must fail - <%_ if (!reactive) { _%> - rest<%= entityClass %>MockMvc.perform(post(ENTITY_API_URL)<% if (testsNeedCsrf) { %>.with(csrf())<% }%> - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))) - .andExpect(status().isBadRequest()); - <%_ } else { _%> + <%_ if (reactive) { _%> webTestClient.post().uri(ENTITY_API_URL) .contentType(MediaType.APPLICATION_JSON) .bodyValue(TestUtil.convertObjectToJsonBytes(<%= restInstance %>)) .exchange() .expectStatus().isBadRequest(); + <%_ } else { _%> + rest<%= entityClass %>MockMvc.perform(post(ENTITY_API_URL)<% if (testsNeedCsrf) { %>.with(csrf())<% }%> + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))) + .andExpect(status().isBadRequest()); <%_ } _%> // Validate the <%= entityClass %> in the database @@ -767,8 +766,8 @@ _%> let required = false; if (!field.fieldTypeBytes && field.fieldValidate && field.fieldValidationRequired) { required = true; - } - if (required) { _%> + } _%> + <%_ if (required) { _%> @Test<%= transactionalAnnotation %> void check<%= field.fieldInJavaBeanMethod %>IsRequired() throws Exception { @@ -780,17 +779,17 @@ _%> <%= dtoClass %> <%= dtoInstance %> = <%= entityInstance %>Mapper.toDto(<%= persistInstance %>);<% } %> - <%_ if (!reactive) { _%> - rest<%= entityClass %>MockMvc.perform(post(ENTITY_API_URL)<% if (testsNeedCsrf) { %>.with(csrf())<% }%> - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))) - .andExpect(status().isBadRequest()); - <%_ } else { _%> + <%_ if (reactive) { _%> webTestClient.post().uri(ENTITY_API_URL) .contentType(MediaType.APPLICATION_JSON) .bodyValue(TestUtil.convertObjectToJsonBytes(<%= restInstance %>)) .exchange() .expectStatus().isBadRequest(); + <%_ } else { _%> + rest<%= entityClass %>MockMvc.perform(post(ENTITY_API_URL)<% if (testsNeedCsrf) { %>.with(csrf())<% }%> + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))) + .andExpect(status().isBadRequest()); <%_ } _%> <%_ if (databaseTypeCouchbase) { _%> @@ -858,17 +857,17 @@ _%> <%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>; // Get all the <%= entityInstance %>List -<%_ if (!reactive) { _%> - rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL<% if (!databaseTypeCassandra) { %> + "?sort=<%= primaryKey.name %>,desc"<% } %>)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) -<%_ } else { _%> +<%_ if (reactive) { _%> webTestClient.get().uri(ENTITY_API_URL + "?sort=<%= primaryKey.name %>,desc") .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() .expectHeader().contentType(MediaType.APPLICATION_JSON) .expectBody() +<%_ } else { _%> + rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL<% if (!databaseTypeCassandra) { %> + "?sort=<%= primaryKey.name %>,desc"<% } %>)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) <%_ } _%> <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeCassandra) { _%> <%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.[*].<%= primaryKey.name %>").value(hasItem(<%= idValue %>))<%= !reactive ? ')' : '' %><%_ } _%><% for (field of fields.filter(field => !field.id && !field.transient)) { %> @@ -893,18 +892,18 @@ _%> @SuppressWarnings({"unchecked"}) void getAll<%= entityClassPlural %>WithEagerRelationshipsIsEnabled() <% if (!reactive) { %>throws Exception <% } %>{ <%_ if (!serviceNo) { _%> - when(<%= entityInstance %>ServiceMock.findAllWithEagerRelationships(any())).thenReturn(<% if (!reactive) { %>new PageImpl(new ArrayList<>())<% } else { %>Flux.empty()<% }%>); + when(<%= entityInstance %>ServiceMock.findAllWithEagerRelationships(any())).thenReturn(<% if (reactive) { %>Flux.empty()<% } else { %>new PageImpl(new ArrayList<>())<% }%>); <%_ } else { _%> - when(<%= entityInstance %>RepositoryMock.findAllWithEagerRelationships(any())).thenReturn(<% if (!reactive) { %>new PageImpl(new ArrayList<>())<% } else { %>Flux.empty()<% }%>); + when(<%= entityInstance %>RepositoryMock.findAllWithEagerRelationships(any())).thenReturn(<% if (reactive) { %>Flux.empty()<% } else { %>new PageImpl(new ArrayList<>())<% }%>); <%_ } _%> - <%_ if (!reactive) { _%> - rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL + "?eagerload=true")) - .andExpect(status().isOk()); - <%_ } else { _%> + <%_ if (reactive) { _%> webTestClient.get().uri(ENTITY_API_URL + "?eagerload=true") .exchange() .expectStatus().isOk(); + <%_ } else { _%> + rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL + "?eagerload=true")) + .andExpect(status().isOk()); <%_ } _%> <%_ if (!serviceNo) { _%> @@ -917,18 +916,18 @@ _%> @SuppressWarnings({"unchecked"}) void getAll<%= entityClassPlural %>WithEagerRelationshipsIsNotEnabled() <% if (!reactive) { %>throws Exception <% } %>{ <%_ if (!serviceNo) { _%> - when(<%= entityInstance %>ServiceMock.findAllWithEagerRelationships(any())).thenReturn(<% if (!reactive) { %>new PageImpl(new ArrayList<>())<% } else { %>Flux.empty()<% }%>); + when(<%= entityInstance %>ServiceMock.findAllWithEagerRelationships(any())).thenReturn(<% if (reactive) { %>Flux.empty()<% } else { %>new PageImpl(new ArrayList<>())<% }%>); <%_ } else { _%> - when(<%= entityInstance %>RepositoryMock.findAllWithEagerRelationships(any())).thenReturn(<% if (!reactive) { %>new PageImpl(new ArrayList<>())<% } else { %>Flux.empty()<% }%>); + when(<%= entityInstance %>RepositoryMock.findAllWithEagerRelationships(any())).thenReturn(<% if (reactive) { %>Flux.empty()<% } else { %>new PageImpl(new ArrayList<>())<% }%>); <%_ } _%> - <%_ if (!reactive) { _%> - rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL + "?eagerload=true")) - .andExpect(status().isOk()); - <%_ } else { _%> + <%_ if (reactive) { _%> webTestClient.get().uri(ENTITY_API_URL + "?eagerload=true") .exchange() .expectStatus().isOk(); + <%_ } else { _%> + rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL + "?eagerload=true")) + .andExpect(status().isOk()); <%_ } _%> <%_ if (!serviceNo) { _%> @@ -950,17 +949,17 @@ _%> <%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>; // Get the <%= entityInstance %> -<%_ if (!reactive) { _%> - rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL_ID, <%= persistInstance %>.get<%= primaryKey.nameCapitalized %>())) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) -<%_ } else { _%> +<%_ if (reactive) { _%> webTestClient.get().uri(ENTITY_API_URL_ID, <%= persistInstance %>.get<%= primaryKey.nameCapitalized %>()) .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() .expectHeader().contentType(MediaType.APPLICATION_JSON) .expectBody() +<%_ } else { _%> + rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL_ID, <%= persistInstance %>.get<%= primaryKey.nameCapitalized %>())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) <%_ } _%> <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeCassandra) { _%> <%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.<%= primaryKey.name %>").value(<%= reactive ? 'is(' : '' %><%= idValue %>))<%_ } _%><% for (field of fields.filter(field => !field.id && !field.transient)) { %> @@ -1313,14 +1312,14 @@ _%> @Test<%= transactionalAnnotation %> void getNonExisting<%= entityClass %>() <% if (!reactive) { %>throws Exception <% } %>{ // Get the <%= entityInstance %> -<%_ if (!reactive) { _%> - rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL_ID, <% if (primaryKey.typeLong || primaryKey.typeString) { %>Long.MAX_VALUE<% } else if (primaryKey.typeUUID) { %>UUID.randomUUID().toString()<% } %>)) - .andExpect(status().isNotFound()); -<%_ } else { _%> +<%_ if (reactive) { _%> webTestClient.get().uri(ENTITY_API_URL_ID, <% if (primaryKey.typeLong || primaryKey.typeString) { %>Long.MAX_VALUE<% } else if (primaryKey.typeUUID) { %>UUID.randomUUID().toString()<% } %>) .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isNotFound(); +<%_ } else { _%> + rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL_ID, <% if (primaryKey.typeLong || primaryKey.typeString) { %>Long.MAX_VALUE<% } else if (primaryKey.typeUUID) { %>UUID.randomUUID().toString()<% } %>)) + .andExpect(status().isNotFound()); <%_ } _%> } <%_ if (!readOnly) { _%> @@ -1364,17 +1363,17 @@ _%> <%= dtoClass %> <%= dtoInstance %> = <%= entityInstance %>Mapper.toDto(updated<%= persistClass %>); <%_ } _%> - <%_ if (!reactive) { _%> - rest<%= entityClass %>MockMvc.perform(put(ENTITY_API_URL_ID, <%= (dtoMapstruct ? asDto(entityInstance) : 'updated' + persistClass) %>.get<%= primaryKey.nameCapitalized %>())<% if (testsNeedCsrf) { %>.with(csrf())<% }%> - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(<%= (dtoMapstruct ? asDto(entityInstance) : 'updated' + persistClass) %>))) - .andExpect(status().isOk()); - <%_ } else { _%> + <%_ if (reactive) { _%> webTestClient.put().uri(ENTITY_API_URL_ID, <%= (dtoMapstruct ? asDto(entityInstance) : 'updated' + persistClass) %>.get<%= primaryKey.nameCapitalized %>()) .contentType(MediaType.APPLICATION_JSON) .bodyValue(TestUtil.convertObjectToJsonBytes(<%= (dtoMapstruct ? asDto(entityInstance) : 'updated' + persistClass) %>)) .exchange() .expectStatus().isOk(); + <%_ } else { _%> + rest<%= entityClass %>MockMvc.perform(put(ENTITY_API_URL_ID, <%= (dtoMapstruct ? asDto(entityInstance) : 'updated' + persistClass) %>.get<%= primaryKey.nameCapitalized %>())<% if (testsNeedCsrf) { %>.with(csrf())<% }%> + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(<%= (dtoMapstruct ? asDto(entityInstance) : 'updated' + persistClass) %>))) + .andExpect(status().isOk()); <%_ } _%> // Validate the <%= entityClass %> in the database @@ -1414,17 +1413,17 @@ _%> <%_ } _%> // If the entity doesn't have an ID, it will throw BadRequestAlertException - <%_ if (!reactive) { _%> - rest<%= entityClass %>MockMvc.perform(put(ENTITY_API_URL_ID, <%= restInstance %>.get<%= primaryKey.nameCapitalized %>())<% if (testsNeedCsrf) { %>.with(csrf())<% }%> - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))) - .andExpect(status().isBadRequest()); - <%_ } else { _%> + <%_ if (reactive) { _%> webTestClient.put().uri(ENTITY_API_URL_ID, <%= restInstance %>.get<%= primaryKey.nameCapitalized %>()) .contentType(MediaType.APPLICATION_JSON) .bodyValue(TestUtil.convertObjectToJsonBytes(<%= restInstance %>)) .exchange() .expectStatus().isBadRequest(); + <%_ } else { _%> + rest<%= entityClass %>MockMvc.perform(put(ENTITY_API_URL_ID, <%= restInstance %>.get<%= primaryKey.nameCapitalized %>())<% if (testsNeedCsrf) { %>.with(csrf())<% }%> + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))) + .andExpect(status().isBadRequest()); <%_ } _%> // Validate the <%= entityClass %> in the database @@ -1451,17 +1450,17 @@ _%> <%_ } _%> // If url ID doesn't match entity ID, it will throw BadRequestAlertException - <%_ if (!reactive) { _%> - rest<%= entityClass %>MockMvc.perform(put(ENTITY_API_URL_ID, <%- getJavaValueGeneratorForType(primaryKey.type) %>)<% if (testsNeedCsrf) { %>.with(csrf())<% } %> - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))) - .andExpect(status().isBadRequest()); - <%_ } else { _%> + <%_ if (reactive) { _%> webTestClient.put().uri(ENTITY_API_URL_ID, <%- getJavaValueGeneratorForType(primaryKey.type) %>) .contentType(MediaType.APPLICATION_JSON) .bodyValue(TestUtil.convertObjectToJsonBytes(<%= restInstance %>)) .exchange() .expectStatus().isBadRequest(); + <%_ } else { _%> + rest<%= entityClass %>MockMvc.perform(put(ENTITY_API_URL_ID, <%- getJavaValueGeneratorForType(primaryKey.type) %>)<% if (testsNeedCsrf) { %>.with(csrf())<% } %> + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))) + .andExpect(status().isBadRequest()); <%_ } _%> // Validate the <%= entityClass %> in the database @@ -1488,17 +1487,17 @@ _%> <%_ } _%> // If url ID doesn't match entity ID, it will throw BadRequestAlertException - <%_ if (!reactive) { _%> - rest<%= entityClass %>MockMvc.perform(put(ENTITY_API_URL)<% if (testsNeedCsrf) { %>.with(csrf())<% } %> - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))) - .andExpect(status().isMethodNotAllowed()); - <%_ } else { _%> + <%_ if (reactive) { _%> webTestClient.put().uri(ENTITY_API_URL) .contentType(MediaType.APPLICATION_JSON) .bodyValue(TestUtil.convertObjectToJsonBytes(<%= restInstance %>)) .exchange() .expectStatus().isEqualTo(405); + <%_ } else { _%> + rest<%= entityClass %>MockMvc.perform(put(ENTITY_API_URL)<% if (testsNeedCsrf) { %>.with(csrf())<% } %> + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))) + .andExpect(status().isMethodNotAllowed()); <%_ } _%> // Validate the <%= entityClass %> in the database @@ -1562,17 +1561,17 @@ _%> <%_ } _%> // If the entity doesn't have an ID, it will throw BadRequestAlertException - <%_ if (!reactive) { _%> - rest<%= entityClass %>MockMvc.perform(patch(ENTITY_API_URL_ID, <%= (dtoMapstruct ? asDto(entityInstance) : asEntity(entityInstance)) %>.get<%= primaryKey.nameCapitalized %>())<% if (testsNeedCsrf) { %>.with(csrf())<% }%> - .contentType("application/merge-patch+json") - .content(TestUtil.convertObjectToJsonBytes(<%= (dtoMapstruct ? asDto(entityInstance) : asEntity(entityInstance)) %>))) - .andExpect(status().isBadRequest()); - <%_ } else { _%> - webTestClient.patch().uri(ENTITY_API_URL_ID, <%= (dtoMapstruct ? asDto(entityInstance) : asEntity(entityInstance)) %>.get<%= primaryKey.nameCapitalized %>()) + <%_ if (reactive) { _%> + webTestClient.patch().uri(ENTITY_API_URL_ID, <%= (dtoMapstruct ? asDto(entityInstance) : asEntity(entityInstance)) %>.get<%= primaryKey.nameCapitalized %>()) .contentType(MediaType.valueOf("application/merge-patch+json")) .bodyValue(TestUtil.convertObjectToJsonBytes(<%= (dtoMapstruct ? asDto(entityInstance) : asEntity(entityInstance)) %>)) .exchange() .expectStatus().isBadRequest(); + <%_ } else { _%> + rest<%= entityClass %>MockMvc.perform(patch(ENTITY_API_URL_ID, <%= (dtoMapstruct ? asDto(entityInstance) : asEntity(entityInstance)) %>.get<%= primaryKey.nameCapitalized %>())<% if (testsNeedCsrf) { %>.with(csrf())<% }%> + .contentType("application/merge-patch+json") + .content(TestUtil.convertObjectToJsonBytes(<%= (dtoMapstruct ? asDto(entityInstance) : asEntity(entityInstance)) %>))) + .andExpect(status().isBadRequest()); <%_ } _%> // Validate the <%= entityClass %> in the database @@ -1599,17 +1598,17 @@ _%> <%_ } _%> // If url ID doesn't match entity ID, it will throw BadRequestAlertException - <%_ if (!reactive) { _%> - rest<%= entityClass %>MockMvc.perform(patch(ENTITY_API_URL_ID, <%- getJavaValueGeneratorForType(primaryKey.type) %>)<% if (testsNeedCsrf) { %>.with(csrf())<% } %> - .contentType("application/merge-patch+json") - .content(TestUtil.convertObjectToJsonBytes(<%= (dtoMapstruct ? asDto(entityInstance) : asEntity(entityInstance)) %>))) - .andExpect(status().isBadRequest()); - <%_ } else { _%> - webTestClient.patch().uri(ENTITY_API_URL_ID, <%- getJavaValueGeneratorForType(primaryKey.type) %>) + <%_ if (reactive) { _%> + webTestClient.patch().uri(ENTITY_API_URL_ID, <%- getJavaValueGeneratorForType(primaryKey.type) %>) .contentType(MediaType.valueOf("application/merge-patch+json")) .bodyValue(TestUtil.convertObjectToJsonBytes(<%= (dtoMapstruct ? asDto(entityInstance) : asEntity(entityInstance)) %>)) .exchange() .expectStatus().isBadRequest(); + <%_ } else { _%> + rest<%= entityClass %>MockMvc.perform(patch(ENTITY_API_URL_ID, <%- getJavaValueGeneratorForType(primaryKey.type) %>)<% if (testsNeedCsrf) { %>.with(csrf())<% } %> + .contentType("application/merge-patch+json") + .content(TestUtil.convertObjectToJsonBytes(<%= (dtoMapstruct ? asDto(entityInstance) : asEntity(entityInstance)) %>))) + .andExpect(status().isBadRequest()); <%_ } _%> // Validate the <%= entityClass %> in the database @@ -1636,17 +1635,17 @@ _%> <%_ } _%> // If url ID doesn't match entity ID, it will throw BadRequestAlertException - <%_ if (!reactive) { _%> - rest<%= entityClass %>MockMvc.perform(patch(ENTITY_API_URL)<% if (testsNeedCsrf) { %>.with(csrf())<% } %> - .contentType("application/merge-patch+json") - .content(TestUtil.convertObjectToJsonBytes(<%= (dtoMapstruct ? asDto(entityInstance) : asEntity(entityInstance)) %>))) - .andExpect(status().isMethodNotAllowed()); - <%_ } else { _%> - webTestClient.patch().uri(ENTITY_API_URL) + <%_ if (reactive) { _%> + webTestClient.patch().uri(ENTITY_API_URL) .contentType(MediaType.valueOf("application/merge-patch+json")) .bodyValue(TestUtil.convertObjectToJsonBytes(<%= (dtoMapstruct ? asDto(entityInstance) : asEntity(entityInstance)) %>)) .exchange() .expectStatus().isEqualTo(405); + <%_ } else { _%> + rest<%= entityClass %>MockMvc.perform(patch(ENTITY_API_URL)<% if (testsNeedCsrf) { %>.with(csrf())<% } %> + .contentType("application/merge-patch+json") + .content(TestUtil.convertObjectToJsonBytes(<%= (dtoMapstruct ? asDto(entityInstance) : asEntity(entityInstance)) %>))) + .andExpect(status().isMethodNotAllowed()); <%_ } _%> // Validate the <%= entityClass %> in the database @@ -1683,15 +1682,15 @@ _%> int databaseSizeBeforeDelete = <%= entityInstance %>Repository.findAll()<%= callListBlock %>.size(); // Delete the <%= entityInstance %> - <%_ if (!reactive) { _%> - rest<%= entityClass %>MockMvc.perform(delete(ENTITY_API_URL_ID, <%= persistInstance %>.get<%= primaryKey.nameCapitalized %>()<% if (primaryKey.typeUUID && databaseTypeSql) { %>.toString()<% } %>)<% if (testsNeedCsrf) { %>.with(csrf())<% }%> - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isNoContent()); - <%_ } else { _%> + <%_ if (reactive) { _%> webTestClient.delete().uri(ENTITY_API_URL_ID, <%= persistInstance %>.get<%= primaryKey.nameCapitalized %>()) .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isNoContent(); + <%_ } else { _%> + rest<%= entityClass %>MockMvc.perform(delete(ENTITY_API_URL_ID, <%= persistInstance %>.get<%= primaryKey.nameCapitalized %>()<% if (primaryKey.typeUUID && databaseTypeSql) { %>.toString()<% } %>)<% if (testsNeedCsrf) { %>.with(csrf())<% }%> + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()); <%_ } _%> // Validate the database contains one less item @@ -1748,16 +1747,16 @@ _%> <%_ } _%> // Search the <%= entityInstance %> - <%_ if (!reactive) { _%> - rest<%= entityClass %>MockMvc.perform(get(ENTITY_SEARCH_API_URL + "?query=id:" + <%= persistInstance %>.get<%= primaryKey.nameCapitalized %>())) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) - <%_ } else { _%> + <%_ if (reactive) { _%> webTestClient.get().uri(ENTITY_SEARCH_API_URL + "?query=id:" + <%= persistInstance %>.get<%= primaryKey.nameCapitalized %>()) .exchange() .expectStatus().isOk() .expectHeader().contentType(MediaType.APPLICATION_JSON) .expectBody() + <%_ } else { _%> + rest<%= entityClass %>MockMvc.perform(get(ENTITY_SEARCH_API_URL + "?query=id:" + <%= persistInstance %>.get<%= primaryKey.nameCapitalized %>())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) <%_ } _%> <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeCassandra) { _%> <%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.[*].<%= primaryKey.name %>").value(hasItem(<%= idValue %>))<%= !reactive ? ')' : '' %><%_ } _%><% for (field of fields.filter(field => !field.id && !field.transient)) { %> diff --git a/generators/server/templates/pom.xml.ejs b/generators/server/templates/pom.xml.ejs index 05a43c35a32..1fb7c1e7447 100644 --- a/generators/server/templates/pom.xml.ejs +++ b/generators/server/templates/pom.xml.ejs @@ -220,17 +220,17 @@ com.fasterxml.jackson.module jackson-module-jaxb-annotations - <%_ if (!reactive) { _%> - - com.fasterxml.jackson.datatype - jackson-datatype-hibernate5 - - <%_ } else { _%> + <%_ if (reactive) { _%> commons-beanutils commons-beanutils ${commons-beanutils.version} + <%_ } else { _%> + + com.fasterxml.jackson.datatype + jackson-datatype-hibernate5 + <%_ } _%> <%_ } _%> diff --git a/generators/server/templates/src/main/java/package/config/LiquibaseConfiguration.java.ejs b/generators/server/templates/src/main/java/package/config/LiquibaseConfiguration.java.ejs index 9833f75c0eb..b211c49a841 100644 --- a/generators/server/templates/src/main/java/package/config/LiquibaseConfiguration.java.ejs +++ b/generators/server/templates/src/main/java/package/config/LiquibaseConfiguration.java.ejs @@ -19,10 +19,10 @@ package <%= packageName %>.config; import tech.jhipster.config.JHipsterConstants; -<%_ if (!reactive) { _%> -import tech.jhipster.config.liquibase.SpringLiquibaseUtil; -<%_ } else { _%> +<%_ if (reactive) { _%> import tech.jhipster.config.liquibase.AsyncSpringLiquibase; +<%_ } else { _%> +import tech.jhipster.config.liquibase.SpringLiquibaseUtil; <%_ } _%> import liquibase.integration.spring.SpringLiquibase; import org.slf4j.Logger; @@ -63,14 +63,14 @@ public class LiquibaseConfiguration { @Bean public SpringLiquibase liquibase(@Qualifier("taskExecutor") Executor executor,<% if (!reactive) { %> @LiquibaseDataSource ObjectProvider liquibaseDataSource,<% } %> LiquibaseProperties liquibaseProperties, - <% if (!reactive) { %>ObjectProvider dataSource, DataSource<% } else { %>R2dbc<% } %>Properties dataSourceProperties) { + <% if (reactive) { %>R2dbc<% } else { %>ObjectProvider dataSource, DataSource<% } %>Properties dataSourceProperties) { -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + SpringLiquibase liquibase = createAsyncSpringLiquibase(this.env, executor, liquibaseProperties, dataSourceProperties); +<%_ } else { _%> // 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); -<%_ } else { _%> - SpringLiquibase liquibase = createAsyncSpringLiquibase(this.env, executor, liquibaseProperties, dataSourceProperties); <%_ } _%> liquibase.setChangeLog("classpath:config/liquibase/master.xml"); liquibase.setContexts(liquibaseProperties.getContexts()); diff --git a/generators/server/templates/src/main/java/package/config/LocaleConfiguration.java.ejs b/generators/server/templates/src/main/java/package/config/LocaleConfiguration.java.ejs index 8f346e63d26..bff40ee5f67 100644 --- a/generators/server/templates/src/main/java/package/config/LocaleConfiguration.java.ejs +++ b/generators/server/templates/src/main/java/package/config/LocaleConfiguration.java.ejs @@ -18,33 +18,7 @@ -%> package <%= packageName %>.config; -<%_ if (!reactive) { _%> -import tech.jhipster.config.locale.AngularCookieLocaleResolver; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.LocaleResolver; -import org.springframework.web.servlet.config.annotation.*; -import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; - -@Configuration -public class LocaleConfiguration implements WebMvcConfigurer { - - @Bean - public LocaleResolver localeResolver() { - AngularCookieLocaleResolver cookieLocaleResolver = new AngularCookieLocaleResolver(); - cookieLocaleResolver.setCookieName("NG_TRANSLATE_LANG_KEY"); - return cookieLocaleResolver; - } - - @Override - public void addInterceptors(InterceptorRegistry registry) { - LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); - localeChangeInterceptor.setParamName("language"); - registry.addInterceptor(localeChangeInterceptor); - } -} -<%_ } else { _%> +<%_ if (reactive) { _%> import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.context.annotation.Bean; @@ -71,143 +45,169 @@ import java.util.TimeZone; @Configuration public class LocaleConfiguration { - @Bean(name = "localeContextResolver") - public LocaleContextResolver localeContextResolver() { - return new AngularCookieLocaleContextResolver(); - } +@Bean(name = "localeContextResolver") +public LocaleContextResolver localeContextResolver() { +return new AngularCookieLocaleContextResolver(); +} + +@Bean +public WebFilter localeChangeFilter(LocaleContextResolver localeContextResolver) { +return (exchange, chain) -> { +// Find locale change in query param. Must also look form params ? +String newLocale = exchange.getRequest().getQueryParams().getFirst("language"); +if (newLocale != null) { +localeContextResolver.setLocaleContext(exchange, new SimpleLocaleContext(StringUtils.parseLocaleString(newLocale))); +} +// Proceed in any case. +return chain.filter(exchange); +}; +} + +static class AngularCookieLocaleContextResolver implements LocaleContextResolver { + +private static final String LOCALE_REQUEST_ATTRIBUTE_NAME = AngularCookieLocaleContextResolver.class.getName() + ".LOCALE"; + +private static final String TIME_ZONE_REQUEST_ATTRIBUTE_NAME = AngularCookieLocaleContextResolver.class.getName() + ".TIME_ZONE"; + +private static final String QUOTE = "%22"; + +private static final String COOKIE_NAME = "NG_TRANSLATE_LANG_KEY"; + +private static final String COOKIE_PATH = "/"; + +protected final Log logger = LogFactory.getLog(getClass()); + +@Override +@Nonnull +public LocaleContext resolveLocaleContext(@Nonnull ServerWebExchange exchange) { +parseLocaleCookieIfNecessary(exchange); +return new TimeZoneAwareLocaleContext() { +@Override +public Locale getLocale() { +return (Locale) exchange.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME); +} + +@Override +public TimeZone getTimeZone() { +return (TimeZone) exchange.getAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME); +} +}; +} + +@Override +public void setLocaleContext(@Nonnull ServerWebExchange exchange, LocaleContext localeContext) { +Assert.notNull(exchange.getResponse() +, "ServerHttpResponse is required for AngularCookieLocaleContextResolver"); + +Locale locale = null; +TimeZone timeZone = null; +if (localeContext != null) { +locale = localeContext.getLocale(); +if (localeContext instanceof TimeZoneAwareLocaleContext) { +timeZone = ((TimeZoneAwareLocaleContext) localeContext).getTimeZone(); +} +addCookie(exchange.getResponse(), +QUOTE + (locale != null ? locale.toString() : "-") + (timeZone != null ? ' ' + timeZone.getID() : "") + QUOTE); +} +else { +removeCookie(exchange.getResponse()); +} +exchange.getAttributes().put(LOCALE_REQUEST_ATTRIBUTE_NAME, +(locale != null ? locale : LocaleContextHolder.getLocale(exchange.getLocaleContext()))); +if (timeZone != null) { +exchange.getAttributes().put(TIME_ZONE_REQUEST_ATTRIBUTE_NAME, timeZone); +} else { +exchange.getAttributes().remove(TIME_ZONE_REQUEST_ATTRIBUTE_NAME); +} +} + +private void addCookie(@Nonnull ServerHttpResponse response, String cookieValue) { +Assert.notNull(response, "ServerHttpResponse must not be null"); +ResponseCookie cookie = ResponseCookie.from(COOKIE_NAME, cookieValue) +.path(COOKIE_PATH) +.build(); +response.addCookie(cookie); +if (logger.isDebugEnabled()) { +logger.debug("Added cookie with name [" + COOKIE_NAME + "] and value [" + cookieValue + "]"); +} +} + +private void removeCookie(@Nonnull ServerHttpResponse response) { +Assert.notNull(response, "ServerHttpResponse must not be null"); +ResponseCookie cookie = ResponseCookie.from(COOKIE_NAME, "") +.path(COOKIE_PATH) +.maxAge(Duration.ZERO) +.build(); +response.addCookie(cookie); +if (logger.isDebugEnabled()) { +logger.debug("Removed cookie with name [" + COOKIE_NAME + "]"); +} +} + +private void parseLocaleCookieIfNecessary(ServerWebExchange exchange) { +if (exchange.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME) == null) { +// Retrieve and parse cookie value. +HttpCookie cookie = exchange.getRequest().getCookies().getFirst(COOKIE_NAME); +Locale locale = null; +TimeZone timeZone = null; +if (cookie != null) { +String value = cookie.getValue(); + +// Remove the double quote +value = StringUtils.replace(value, QUOTE, ""); + +String localePart = value; +String timeZonePart = null; +int spaceIndex = localePart.indexOf(' '); +if (spaceIndex != -1) { +localePart = value.substring(0, spaceIndex); +timeZonePart = value.substring(spaceIndex + 1); +} +locale = !"-".equals(localePart) ? StringUtils.parseLocaleString(localePart.replace('-', '_')) : null; +if (timeZonePart != null) { +timeZone = StringUtils.parseTimeZoneString(timeZonePart); +} +if (logger.isTraceEnabled()) { +logger.trace("Parsed cookie value [" + cookie.getValue() + "] into locale '" + locale + +"'" + (timeZone != null ? " and time zone '" + timeZone.getID() + "'" : "")); +} +} +if (locale != null) { +exchange.getAttributes().put(LOCALE_REQUEST_ATTRIBUTE_NAME, locale); +} +if (timeZone != null) { +exchange.getAttributes().put(TIME_ZONE_REQUEST_ATTRIBUTE_NAME, timeZone); +} else { +exchange.getAttributes().remove(TIME_ZONE_REQUEST_ATTRIBUTE_NAME); +} +} +} +} +} +<%_ } else { _%> +import tech.jhipster.config.locale.AngularCookieLocaleResolver; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.LocaleResolver; +import org.springframework.web.servlet.config.annotation.*; +import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; + +@Configuration +public class LocaleConfiguration implements WebMvcConfigurer { @Bean - public WebFilter localeChangeFilter(LocaleContextResolver localeContextResolver) { - return (exchange, chain) -> { - // Find locale change in query param. Must also look form params ? - String newLocale = exchange.getRequest().getQueryParams().getFirst("language"); - if (newLocale != null) { - localeContextResolver.setLocaleContext(exchange, new SimpleLocaleContext(StringUtils.parseLocaleString(newLocale))); - } - // Proceed in any case. - return chain.filter(exchange); - }; + public LocaleResolver localeResolver() { + AngularCookieLocaleResolver cookieLocaleResolver = new AngularCookieLocaleResolver(); + cookieLocaleResolver.setCookieName("NG_TRANSLATE_LANG_KEY"); + return cookieLocaleResolver; } - static class AngularCookieLocaleContextResolver implements LocaleContextResolver { - - private static final String LOCALE_REQUEST_ATTRIBUTE_NAME = AngularCookieLocaleContextResolver.class.getName() + ".LOCALE"; - - private static final String TIME_ZONE_REQUEST_ATTRIBUTE_NAME = AngularCookieLocaleContextResolver.class.getName() + ".TIME_ZONE"; - - private static final String QUOTE = "%22"; - - private static final String COOKIE_NAME = "NG_TRANSLATE_LANG_KEY"; - - private static final String COOKIE_PATH = "/"; - - protected final Log logger = LogFactory.getLog(getClass()); - - @Override - @Nonnull - public LocaleContext resolveLocaleContext(@Nonnull ServerWebExchange exchange) { - parseLocaleCookieIfNecessary(exchange); - return new TimeZoneAwareLocaleContext() { - @Override - public Locale getLocale() { - return (Locale) exchange.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME); - } - - @Override - public TimeZone getTimeZone() { - return (TimeZone) exchange.getAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME); - } - }; - } - - @Override - public void setLocaleContext(@Nonnull ServerWebExchange exchange, LocaleContext localeContext) { - Assert.notNull(exchange.getResponse() - , "ServerHttpResponse is required for AngularCookieLocaleContextResolver"); - - Locale locale = null; - TimeZone timeZone = null; - if (localeContext != null) { - locale = localeContext.getLocale(); - if (localeContext instanceof TimeZoneAwareLocaleContext) { - timeZone = ((TimeZoneAwareLocaleContext) localeContext).getTimeZone(); - } - addCookie(exchange.getResponse(), - QUOTE + (locale != null ? locale.toString() : "-") + (timeZone != null ? ' ' + timeZone.getID() : "") + QUOTE); - } - else { - removeCookie(exchange.getResponse()); - } - exchange.getAttributes().put(LOCALE_REQUEST_ATTRIBUTE_NAME, - (locale != null ? locale : LocaleContextHolder.getLocale(exchange.getLocaleContext()))); - if (timeZone != null) { - exchange.getAttributes().put(TIME_ZONE_REQUEST_ATTRIBUTE_NAME, timeZone); - } else { - exchange.getAttributes().remove(TIME_ZONE_REQUEST_ATTRIBUTE_NAME); - } - } - - private void addCookie(@Nonnull ServerHttpResponse response, String cookieValue) { - Assert.notNull(response, "ServerHttpResponse must not be null"); - ResponseCookie cookie = ResponseCookie.from(COOKIE_NAME, cookieValue) - .path(COOKIE_PATH) - .build(); - response.addCookie(cookie); - if (logger.isDebugEnabled()) { - logger.debug("Added cookie with name [" + COOKIE_NAME + "] and value [" + cookieValue + "]"); - } - } - - private void removeCookie(@Nonnull ServerHttpResponse response) { - Assert.notNull(response, "ServerHttpResponse must not be null"); - ResponseCookie cookie = ResponseCookie.from(COOKIE_NAME, "") - .path(COOKIE_PATH) - .maxAge(Duration.ZERO) - .build(); - response.addCookie(cookie); - if (logger.isDebugEnabled()) { - logger.debug("Removed cookie with name [" + COOKIE_NAME + "]"); - } - } - - private void parseLocaleCookieIfNecessary(ServerWebExchange exchange) { - if (exchange.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME) == null) { - // Retrieve and parse cookie value. - HttpCookie cookie = exchange.getRequest().getCookies().getFirst(COOKIE_NAME); - Locale locale = null; - TimeZone timeZone = null; - if (cookie != null) { - String value = cookie.getValue(); - - // Remove the double quote - value = StringUtils.replace(value, QUOTE, ""); - - String localePart = value; - String timeZonePart = null; - int spaceIndex = localePart.indexOf(' '); - if (spaceIndex != -1) { - localePart = value.substring(0, spaceIndex); - timeZonePart = value.substring(spaceIndex + 1); - } - locale = !"-".equals(localePart) ? StringUtils.parseLocaleString(localePart.replace('-', '_')) : null; - if (timeZonePart != null) { - timeZone = StringUtils.parseTimeZoneString(timeZonePart); - } - if (logger.isTraceEnabled()) { - logger.trace("Parsed cookie value [" + cookie.getValue() + "] into locale '" + locale + - "'" + (timeZone != null ? " and time zone '" + timeZone.getID() + "'" : "")); - } - } - if (locale != null) { - exchange.getAttributes().put(LOCALE_REQUEST_ATTRIBUTE_NAME, locale); - } - if (timeZone != null) { - exchange.getAttributes().put(TIME_ZONE_REQUEST_ATTRIBUTE_NAME, timeZone); - } else { - exchange.getAttributes().remove(TIME_ZONE_REQUEST_ATTRIBUTE_NAME); - } - } - } + @Override + public void addInterceptors(InterceptorRegistry registry) { + LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); + localeChangeInterceptor.setParamName("language"); + registry.addInterceptor(localeChangeInterceptor); } } <%_ } _%> diff --git a/generators/server/templates/src/main/java/package/domain/Authority.java.ejs b/generators/server/templates/src/main/java/package/domain/Authority.java.ejs index 932c4b69316..b5fc2fdbbb3 100644 --- a/generators/server/templates/src/main/java/package/domain/Authority.java.ejs +++ b/generators/server/templates/src/main/java/package/domain/Authority.java.ejs @@ -31,15 +31,15 @@ import org.springframework.data.neo4j.core.schema.Id; import org.springframework.data.neo4j.core.schema.Node; <%_ } _%> <%_ if (databaseTypeSql) { _%> - <%_ if (!reactive) { _%> + <%_ if (reactive) { _%> +import org.springframework.data.annotation.Id; +import org.springframework.data.domain.Persistable; +import org.springframework.data.relational.core.mapping.Table; + <%_ } else { _%> import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Column; - <%_ } else { _%> -import org.springframework.data.annotation.Id; -import org.springframework.data.domain.Persistable; -import org.springframework.data.relational.core.mapping.Table; <%_ } _%> <%_ } _%> diff --git a/generators/server/templates/src/main/java/package/domain/User.java.ejs b/generators/server/templates/src/main/java/package/domain/User.java.ejs index 66d67c6b29d..ae5cdd4db1d 100644 --- a/generators/server/templates/src/main/java/package/domain/User.java.ejs +++ b/generators/server/templates/src/main/java/package/domain/User.java.ejs @@ -166,10 +166,10 @@ public class <%= asEntity('User') %><% if (databaseTypeSql || databaseTypeMongod @GeneratedValue(strategy = USE_ATTRIBUTES, delimiter = ID_DELIMITER) <%_ } _%> <%_ if (databaseTypeCassandra) { _%> - <%_ if (!reactive) { _%> - @PartitionKey - <%_ } else { _%> + <%_ if (reactive) { _%> @PrimaryKey + <%_ } else { _%> + @PartitionKey <%_ } _%> <%_ } _%> <%_ if (searchEngineElasticsearch) { _%> diff --git a/generators/server/templates/src/main/java/package/repository/AuthorityRepository.java.ejs b/generators/server/templates/src/main/java/package/repository/AuthorityRepository.java.ejs index 282b5e2731e..d30609f71c7 100644 --- a/generators/server/templates/src/main/java/package/repository/AuthorityRepository.java.ejs +++ b/generators/server/templates/src/main/java/package/repository/AuthorityRepository.java.ejs @@ -24,10 +24,10 @@ import org.springframework.stereotype.Repository; <%_ } _%> <%_ if (databaseTypeSql) { _%> - <%_ if (!reactive) { _%> -import org.springframework.data.jpa.repository.JpaRepository; - <%_ } else { _%> + <%_ if (reactive) { _%> import org.springframework.data.r2dbc.repository.R2dbcRepository; + <%_ } else { _%> +import org.springframework.data.jpa.repository.JpaRepository; <%_ } _%> <%_ } _%> <%_ if (databaseTypeMongodb) { _%> diff --git a/generators/server/templates/src/main/java/package/repository/UserRepository.java.ejs b/generators/server/templates/src/main/java/package/repository/UserRepository.java.ejs index 1cb84f23629..8b6c9a258b2 100644 --- a/generators/server/templates/src/main/java/package/repository/UserRepository.java.ejs +++ b/generators/server/templates/src/main/java/package/repository/UserRepository.java.ejs @@ -68,10 +68,7 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; <%_ } _%> <%_ if (databaseTypeSql) { _%> - <%_ if (!reactive) { _%> -import org.springframework.data.jpa.repository.EntityGraph; -import org.springframework.data.jpa.repository.JpaRepository; - <%_ } else { _%> + <%_ if (reactive) { _%> import org.springframework.data.domain.Sort; import org.springframework.r2dbc.core.DatabaseClient; import org.springframework.data.r2dbc.convert.R2dbcConverter; @@ -84,6 +81,9 @@ import org.springframework.data.relational.core.sql.Table; import static org.springframework.data.relational.core.query.Criteria.where; import static org.springframework.data.relational.core.query.Query.query; + <%_ } else { _%> +import org.springframework.data.jpa.repository.EntityGraph; +import org.springframework.data.jpa.repository.JpaRepository; <%_ } _%> <%_ } _%> <%_ if (databaseTypeMongodb) { _%> @@ -473,17 +473,17 @@ public class UserRepository { <%_ } _%> <%_ if (!reactive) { _%> - private final CqlSession session; - <%_ } else { _%> private final ReactiveSession session; + <%_ } else { _%> + private final CqlSession session; <%_ } _%> private final Validator validator; <%_ if (!reactive) { _%> - private UserDao userDao; - <%_ } else { _%> private final ReactiveCassandraTemplate cqlTemplate; + <%_ } else { _%> + private UserDao userDao; <%_ } _%> <%_ if (reactive) { _%> @@ -529,13 +529,13 @@ public class UserRepository { public UserRepository(<% if (reactive) { %>ReactiveCassandraTemplate cqlTemplate, Reactive<% } else { %>Cql<% } %>Session session, Validator validator<% if (!reactive) { %>, CassandraProperties cassandraProperties<% } %>) { this.session = session; this.validator = validator; - <%_ if (!reactive) { _%> - UserTokenMapper userTokenMapper = new UserTokenMapperBuilder(session).build(); - userDao = userTokenMapper.userTokenDao(CqlIdentifier.fromCql(cassandraProperties.getKeyspaceName())); - <%_ } else { _%> + <%_ if (reactive) { _%> this.cqlTemplate = cqlTemplate; findAllStmt = session.prepare("SELECT * FROM user")<% if (reactive) { %>.block()<% } %>; + <%_ } else { _%> + UserTokenMapper userTokenMapper = new UserTokenMapperBuilder(session).build(); + userDao = userTokenMapper.userTokenDao(CqlIdentifier.fromCql(cassandraProperties.getKeyspaceName())); <%_ } _%> findOneByActivationKeyStmt = session.prepare( @@ -606,9 +606,7 @@ public class UserRepository { } public <%= optionalOrMono %><<%= asEntity('User') %>> findById(String id) { - <%_ if (!reactive) { _%> - return userDao.get(id); - <%_ } else { _%> + <%_ if (reactive) { _%> return cqlTemplate.selectOneById(id, <%= asEntity('User') %>.class) .map(user -> { if (user.getAuthorities() == null) { @@ -616,6 +614,8 @@ public class UserRepository { } return user; }); + <%_ } else { _%> + return userDao.get(id); <%_ } _%> } @@ -646,9 +646,7 @@ public class UserRepository { } public <%= listOrFlux %><<%= asEntity('User') %>> findAll() { - <%_ if (!reactive) { _%> - return userDao.findAll().all(); - <%_ } else { _%> + <%_ if (reactive) { _%> return cqlTemplate.select(findAllStmt.bind(), <%= asEntity('User') %>.class) .map(user -> { if (user.getAuthorities() == null) { @@ -656,6 +654,8 @@ public class UserRepository { } return user; }); + <%_ } else { _%> + return userDao.findAll().all(); <%_ } _%> } @@ -664,44 +664,7 @@ public class UserRepository { if (violations != null && !violations.isEmpty()) { throw new ConstraintViolationException(violations); } - <%_ if (!reactive) { _%> - <%= asEntity('User') %> oldUser = userDao.get(user.getId()).orElse(null); - if (oldUser != null) { - if (!StringUtils.isEmpty(oldUser.getActivationKey()) && !oldUser.getActivationKey().equals(user.getActivationKey())) { - session.execute(deleteByActivationKeyStmt.bind().setString("activation_key", oldUser.getActivationKey())); - } - if (!StringUtils.isEmpty(oldUser.getResetKey()) && !oldUser.getResetKey().equals(user.getResetKey())) { - session.execute(deleteByResetKeyStmt.bind().setString("reset_key", oldUser.getResetKey())); - } - if (!StringUtils.isEmpty(oldUser.getLogin()) && !oldUser.getLogin().equals(user.getLogin())) { - session.execute(deleteByLoginStmt.bind().setString("login", oldUser.getLogin())); - } - if (!StringUtils.isEmpty(oldUser.getEmail()) && !oldUser.getEmail().equalsIgnoreCase(user.getEmail())) { - session.execute(deleteByEmailStmt.bind().setString("email", oldUser.getEmail().toLowerCase())); - } - } - BatchStatementBuilder batch = BatchStatement.builder(DefaultBatchType.LOGGED); - batch.addStatement(userDao.saveQuery(user)); - if (!StringUtils.isEmpty(user.getActivationKey())) { - batch.addStatement(insertByActivationKeyStmt.bind() - .setString("activation_key", user.getActivationKey()) - .setString("id", user.getId())); - } - if (!StringUtils.isEmpty(user.getResetKey())) { - batch.addStatement(insertByResetKeyStmt.bind() - .setString("reset_key", user.getResetKey()) - .setString("id", user.getId())); - } - batch.addStatement(insertByLoginStmt.bind() - .setString("login", user.getLogin()) - .setString("id", user.getId())); - batch.addStatement(insertByEmailStmt.bind() - .setString("email", user.getEmail().toLowerCase()) - .setString("id", user.getId())); - session.execute(batch.build()); - return user; - } - <%_ } else { /* reactive */ _%> + <%_ if (reactive) { _%> return this.findById(user.getId()) .flatMapMany(oldUser -> { Flux deleteOps = Flux.empty(); @@ -756,11 +719,48 @@ public class UserRepository { } return insert.build(); } + <%_ } else { /* !reactive */ _%> + <%= asEntity('User') %> oldUser = userDao.get(user.getId()).orElse(null); + if (oldUser != null) { + if (!StringUtils.isEmpty(oldUser.getActivationKey()) && !oldUser.getActivationKey().equals(user.getActivationKey())) { + session.execute(deleteByActivationKeyStmt.bind().setString("activation_key", oldUser.getActivationKey())); + } + if (!StringUtils.isEmpty(oldUser.getResetKey()) && !oldUser.getResetKey().equals(user.getResetKey())) { + session.execute(deleteByResetKeyStmt.bind().setString("reset_key", oldUser.getResetKey())); + } + if (!StringUtils.isEmpty(oldUser.getLogin()) && !oldUser.getLogin().equals(user.getLogin())) { + session.execute(deleteByLoginStmt.bind().setString("login", oldUser.getLogin())); + } + if (!StringUtils.isEmpty(oldUser.getEmail()) && !oldUser.getEmail().equalsIgnoreCase(user.getEmail())) { + session.execute(deleteByEmailStmt.bind().setString("email", oldUser.getEmail().toLowerCase())); + } + } + BatchStatementBuilder batch = BatchStatement.builder(DefaultBatchType.LOGGED); + batch.addStatement(userDao.saveQuery(user)); + if (!StringUtils.isEmpty(user.getActivationKey())) { + batch.addStatement(insertByActivationKeyStmt.bind() + .setString("activation_key", user.getActivationKey()) + .setString("id", user.getId())); + } + if (!StringUtils.isEmpty(user.getResetKey())) { + batch.addStatement(insertByResetKeyStmt.bind() + .setString("reset_key", user.getResetKey()) + .setString("id", user.getId())); + } + batch.addStatement(insertByLoginStmt.bind() + .setString("login", user.getLogin()) + .setString("id", user.getId())); + batch.addStatement(insertByEmailStmt.bind() + .setString("email", user.getEmail().toLowerCase()) + .setString("id", user.getId())); + session.execute(batch.build()); + return user; + } <%_ } _%> public <% if (reactive) { %>Mono<% } else { %>void<% } %> delete(<%= asEntity('User') %> user) { BatchStatementBuilder batch = BatchStatement.builder(DefaultBatchType.LOGGED); - batch.addStatement(<% if (!reactive) { %>userDao.deleteQuery(user)<% } else { %>deleteByIdStmt.bind().setString("id", user.getId())<% } %>); + batch.addStatement(<% if (reactive) { %>deleteByIdStmt.bind().setString("id", user.getId())<% } else { %>userDao.deleteQuery(user)<% } %>); if (!StringUtils.isEmpty(user.getActivationKey())) { batch.addStatement(deleteByActivationKeyStmt.bind().setString("activation_key", user.getActivationKey())); } @@ -769,14 +769,27 @@ public class UserRepository { } batch.addStatement(deleteByLoginStmt.bind().setString("login", user.getLogin())); batch.addStatement(deleteByEmailStmt.bind().setString("email", user.getEmail().toLowerCase())); - <%_ if (!reactive) { _%> - session.execute(batch.build()); - <%_ } else { _%> + <%_ if (reactive) { _%> return session.execute(batch.build()).then(); + <%_ } else { _%> + session.execute(batch.build()); <%_ } _%> } - <%_ if (!reactive) { _%> + <%_ if (reactive) { _%> + private Mono<<%= asEntity('User') %>> findOneFromIndex(BoundStatement stmt) { + return session.execute(stmt).flatMap(rs -> rs.rows().next()) + .map(row -> row.getString("id")) + .flatMap(this::findById); + } + + public Mono deleteAll() { + return Flux.just(truncateStmt, truncateByEmailStmt, truncateByLoginStmt, truncateByResetKeyStmt) + .map(PreparedStatement::bind) + .flatMap(session::execute) + .then(); + } + <%_ } else { _%> private Optional<<%= asEntity('User') %>> findOneFromIndex(BoundStatement stmt) { ResultSet rs = session.execute(stmt); return Optional @@ -798,19 +811,6 @@ public class UserRepository { BoundStatement truncateByResetKey = truncateByResetKeyStmt.bind(); session.execute(truncateByResetKey); } - <%_ } else { _%> - private Mono<<%= asEntity('User') %>> findOneFromIndex(BoundStatement stmt) { - return session.execute(stmt).flatMap(rs -> rs.rows().next()) - .map(row -> row.getString("id")) - .flatMap(this::findById); - } - - public Mono deleteAll() { - return Flux.just(truncateStmt, truncateByEmailStmt, truncateByLoginStmt, truncateByResetKeyStmt) - .map(PreparedStatement::bind) - .flatMap(session::execute) - .then(); - } <%_ } _%> } <%_ if (!reactive) { _%> diff --git a/generators/server/templates/src/main/java/package/security/DomainUserDetailsService.java.ejs b/generators/server/templates/src/main/java/package/security/DomainUserDetailsService.java.ejs index 27feea5bd04..fc2a8250ccb 100644 --- a/generators/server/templates/src/main/java/package/security/DomainUserDetailsService.java.ejs +++ b/generators/server/templates/src/main/java/package/security/DomainUserDetailsService.java.ejs @@ -62,7 +62,7 @@ public class DomainUserDetailsService implements <% if (reactive) { %>Reactive<% <%_ if (databaseTypeSql) { _%> @Transactional <%_ } _%> - public <% if (!reactive) { %>UserDetails loadUserByUsername<% } else { %>Mono findByUsername<% } %>(final String login) { + public <% if (!reactive) { %>Mono findByUsername<% } else { %>UserDetails loadUserByUsername<% } %>(final String login) { log.debug("Authenticating {}", login); if (new EmailValidator().isValid(login, null)) { diff --git a/generators/server/templates/src/main/java/package/security/SecurityUtils.java.ejs b/generators/server/templates/src/main/java/package/security/SecurityUtils.java.ejs index 3a4bca6eed0..b6c87e61abc 100644 --- a/generators/server/templates/src/main/java/package/security/SecurityUtils.java.ejs +++ b/generators/server/templates/src/main/java/package/security/SecurityUtils.java.ejs @@ -70,14 +70,14 @@ public final class SecurityUtils { * * @return the login of the current user. */ - public static <% if (!reactive) { %>Optional<% } else { %>Mono<% } %> getCurrentUserLogin() { -<%_ if (!reactive) { _%> - SecurityContext securityContext = SecurityContextHolder.getContext(); - return Optional.ofNullable(extractPrincipal(securityContext.getAuthentication())); -<%_ } else { _%> + public static <% if (reactive) { %>Mono<% } else { %>Optional<% } %> getCurrentUserLogin() { +<%_ if (reactive) { _%> return ReactiveSecurityContextHolder.getContext() .map(SecurityContext::getAuthentication) .flatMap(authentication -> Mono.justOrEmpty(extractPrincipal(authentication))); +<%_ } else { _%> + SecurityContext securityContext = SecurityContextHolder.getContext(); + return Optional.ofNullable(extractPrincipal(securityContext.getAuthentication())); <%_ } _%> } @@ -109,13 +109,13 @@ public final class SecurityUtils { * * @return the JWT of the current user. */ - public static <% if (!reactive) { %>Optional<% } else { %>Mono<% } %> getCurrentUserJWT() { - <%_ if (!reactive) { _%> - SecurityContext securityContext = SecurityContextHolder.getContext(); - return Optional.ofNullable(securityContext.getAuthentication()) - <%_ } else { _%> + public static <% if (reactive) { %>Mono<% } else { %>Optional<% } %> getCurrentUserJWT() { + <%_ if (reactive) { _%> return ReactiveSecurityContextHolder.getContext() .map(SecurityContext::getAuthentication) + <%_ } else { _%> + SecurityContext securityContext = SecurityContextHolder.getContext(); + return Optional.ofNullable(securityContext.getAuthentication()) <%_ } _%> .filter(authentication -> authentication.getCredentials() instanceof String) .map(authentication -> (String) authentication.getCredentials()); @@ -127,12 +127,8 @@ public final class SecurityUtils { * * @return true if the user is authenticated, false otherwise. */ - public static <% if (!reactive) { %>boolean<% } else { %>Mono<% } %> isAuthenticated() { -<%_ if (!reactive) { _%> - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - return authentication != null && - getAuthorities(authentication).noneMatch(AuthoritiesConstants.ANONYMOUS::equals); -<%_ } else { _%> + public static <% if (reactive) { %>Mono<% } else { %>boolean<% } %> isAuthenticated() { +<%_ if (reactive) { _%> return ReactiveSecurityContextHolder.getContext() .map(SecurityContext::getAuthentication) .map(Authentication::getAuthorities) @@ -140,6 +136,10 @@ public final class SecurityUtils { .map(GrantedAuthority::getAuthority) .noneMatch(AuthoritiesConstants.ANONYMOUS::equals) ); +<%_ } else { _%> + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + return authentication != null && + getAuthorities(authentication).noneMatch(AuthoritiesConstants.ANONYMOUS::equals); <%_ } _%> } @@ -149,13 +149,8 @@ public final class SecurityUtils { * @param authorities the authorities to check. * @return true if the current user has any of the authorities, false otherwise. */ - public static <% if (!reactive) { %>boolean<% } else { %>Mono<% } %> hasCurrentUserAnyOfAuthorities(String... authorities) { -<%_ if (!reactive) { _%> - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - return ( - authentication != null && getAuthorities(authentication).anyMatch(authority -> Arrays.asList(authorities).contains(authority)) - ); -<%_ } else { _%> + public static <% if (reactive) { %>Mono<% } else { %>boolean<% } %> hasCurrentUserAnyOfAuthorities(String... authorities) { +<%_ if (reactive) { _%> return ReactiveSecurityContextHolder.getContext() .map(SecurityContext::getAuthentication) .map(Authentication::getAuthorities) @@ -163,6 +158,11 @@ public final class SecurityUtils { .map(GrantedAuthority::getAuthority) .anyMatch(authority -> Arrays.asList(authorities).contains(authority)) ); +<%_ } else { _%> + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + return ( + authentication != null && getAuthorities(authentication).anyMatch(authority -> Arrays.asList(authorities).contains(authority)) + ); <%_ } _%> } @@ -172,11 +172,11 @@ public final class SecurityUtils { * @param authorities the authorities to check. * @return true if the current user has none of the authorities, false otherwise. */ - public static <% if (!reactive) { %>boolean<% } else { %>Mono<% } %> hasCurrentUserNoneOfAuthorities(String... authorities) { -<%_ if (!reactive) { _%> - return !hasCurrentUserAnyOfAuthorities(authorities); -<%_ } else { _%> + public static <% if (reactive) { %>Mono<% } else { %>boolean<% } %> hasCurrentUserNoneOfAuthorities(String... authorities) { +<%_ if (reactive) { _%> return hasCurrentUserAnyOfAuthorities(authorities).map(result -> !result); +<%_ } else { _%> + return !hasCurrentUserAnyOfAuthorities(authorities); <%_ } _%> } @@ -186,7 +186,7 @@ public final class SecurityUtils { * @param authority the authority to check. * @return true if the current user has the authority, false otherwise. */ - public static <% if (!reactive) { %>boolean<% } else { %>Mono<% } %> hasCurrentUserThisAuthority(String authority) { + public static <% if (reactive) { %>Mono<% } else { %>boolean<% } %> hasCurrentUserThisAuthority(String authority) { return hasCurrentUserAnyOfAuthorities(authority); } diff --git a/generators/server/templates/src/main/java/package/security/jwt/JWTFilter.java.ejs b/generators/server/templates/src/main/java/package/security/jwt/JWTFilter.java.ejs index 9af569b57e4..aa7d21488ce 100644 --- a/generators/server/templates/src/main/java/package/security/jwt/JWTFilter.java.ejs +++ b/generators/server/templates/src/main/java/package/security/jwt/JWTFilter.java.ejs @@ -48,7 +48,7 @@ import java.io.IOException; * Filters incoming requests and installs a Spring Security principal if a header corresponding to a valid user is * found. */ -public class JWTFilter <% if (!reactive) { %>extends GenericFilterBean<% } else { %>implements WebFilter<% } %> { +public class JWTFilter <% if (reactive) { %>implements WebFilter<% } else { %>extends GenericFilterBean<% } %> { public static final String AUTHORIZATION_HEADER = "Authorization"; <%_ if (communicationSpringWebsocket) { _%> @@ -63,14 +63,14 @@ public class JWTFilter <% if (!reactive) { %>extends GenericFilterBean<% } else } @Override -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { + String jwt = resolveToken(exchange.getRequest()); +<%_ } else { _%> public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; String jwt = resolveToken(httpServletRequest); -<%_ } else { _%> - public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { - String jwt = resolveToken(exchange.getRequest()); <%_ } _%> if (StringUtils.hasText(jwt) && this.tokenProvider.validateToken(jwt)) { Authentication authentication = this.tokenProvider.getAuthentication(jwt); @@ -85,8 +85,8 @@ public class JWTFilter <% if (!reactive) { %>extends GenericFilterBean<% } else <%_ } _%> } - private String resolveToken(<% if (!reactive) { %>HttpServletRequest<% } else { %>ServerHttpRequest<% } %> request) { - String bearerToken = request.<% if (!reactive) { %>getHeader<% } else { %>getHeaders().getFirst<% } %>(AUTHORIZATION_HEADER); + private String resolveToken(<% if (reactive) { %>ServerHttpRequest<% } else { %>HttpServletRequest<% } %> request) { + String bearerToken = request.<% if (reactive) { %>getHeaders().getFirst<% } else { %>getHeader<% } %>(AUTHORIZATION_HEADER); if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) { return bearerToken.substring(7); } diff --git a/generators/server/templates/src/main/java/package/service/UserService.java.ejs b/generators/server/templates/src/main/java/package/service/UserService.java.ejs index 667eb6c644b..95b0f32d821 100644 --- a/generators/server/templates/src/main/java/package/service/UserService.java.ejs +++ b/generators/server/templates/src/main/java/package/service/UserService.java.ejs @@ -166,7 +166,17 @@ public class UserService { // activate given user for the registration key. user.setActivated(true); user.setActivationKey(null); - <%_ if (!reactive) { _%> + <%_ if (reactive) { _%> + return saveUser(user); + }) + <%_ if (searchEngineElasticsearch) { _%> + .flatMap(user -> userSearchRepository.save(user).thenReturn(user)) + <%_ } _%> + <%_ if (cacheManagerIsAvailable) { _%> + .doOnNext(this::clearUserCaches) + <%_ } _%> + .doOnNext(user -> log.debug("Activated user: {}", user)); + <%_ } else { _%> <%_ if (databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase || databaseTypeCassandra) { _%> userRepository.save(user); <%_ } _%> @@ -179,16 +189,6 @@ public class UserService { log.debug("Activated user: {}", user); return user; }); - <%_ } else { _%> - return saveUser(user); - }) - <%_ if (searchEngineElasticsearch) { _%> - .flatMap(user -> userSearchRepository.save(user).thenReturn(user)) - <%_ } _%> - <%_ if (cacheManagerIsAvailable) { _%> - .doOnNext(this::clearUserCaches) - <%_ } _%> - .doOnNext(user -> log.debug("Activated user: {}", user)); <%_ } _%> } @@ -199,7 +199,17 @@ public class UserService { log.debug("Reset user password for reset key {}", key); return userRepository.findOneByResetKey(key) .filter(user -> user.getResetDate().isAfter(Instant.now().minus(1, ChronoUnit.DAYS))) - <%_ if (!reactive) { _%> + <%_ if (reactive) { _%> + .publishOn(Schedulers.boundedElastic()) + .map(user -> { + user.setPassword(passwordEncoder.encode(newPassword)); + user.setResetKey(null); + user.setResetDate(null); + return user; + }) + .flatMap(this::saveUser)<% if (cacheManagerIsAvailable) { %> + .doOnNext(this::clearUserCaches)<% } %>; + <%_ } else { _%> .map(user -> { user.setPassword(passwordEncoder.encode(newPassword)); user.setResetKey(null); @@ -212,16 +222,6 @@ public class UserService { <%_ } _%> return user; }); - <%_ } else { _%> - .publishOn(Schedulers.boundedElastic()) - .map(user -> { - user.setPassword(passwordEncoder.encode(newPassword)); - user.setResetKey(null); - user.setResetDate(null); - return user; - }) - .flatMap(this::saveUser)<% if (cacheManagerIsAvailable) { %> - .doOnNext(this::clearUserCaches)<% } %>; <%_ } _%> } @@ -231,7 +231,16 @@ public class UserService { public <% if (reactive) { %>Mono<% } else { %>Optional<% } %><<%= asEntity('User') %>> requestPasswordReset(String mail) { return userRepository.findOneByEmailIgnoreCase(mail) .filter(<%= asEntity('User') %>::isActivated) - <%_ if (!reactive) { _%> + <%_ if (reactive) { _%> + .publishOn(Schedulers.boundedElastic()) + .map(user -> { + user.setResetKey(RandomUtil.generateResetKey()); + user.setResetDate(Instant.now()); + return user; + }) + .flatMap(this::saveUser)<% if (cacheManagerIsAvailable) { %> + .doOnNext(this::clearUserCaches)<% } %>; + <%_ } else { _%> .map(user -> { user.setResetKey(RandomUtil.generateResetKey()); user.setResetDate(Instant.now()); @@ -243,15 +252,6 @@ public class UserService { <%_ } _%> return user; }); - <%_ } else { _%> - .publishOn(Schedulers.boundedElastic()) - .map(user -> { - user.setResetKey(RandomUtil.generateResetKey()); - user.setResetDate(Instant.now()); - return user; - }) - .flatMap(this::saveUser)<% if (cacheManagerIsAvailable) { %> - .doOnNext(this::clearUserCaches)<% } %>; <%_ } _%> } @@ -259,58 +259,7 @@ public class UserService { @Transactional <%_ } _%> public <% if (reactive) { %>Mono<<%= asEntity('User') %>><% } else { %><%= asEntity('User') %><% } %> registerUser(<%= asDto('AdminUser') %> userDTO, String password) { - <%_ if (!reactive) { _%> - 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(); - } - }); - <%= asEntity('User') %> newUser = new <%= asEntity('User') %>(); - <%_ if (databaseTypeCassandra) { _%> - newUser.setId(UUID.randomUUID().toString()); - <%_ } _%> - String encryptedPassword = passwordEncoder.encode(password); - newUser.setLogin(userDTO.getLogin().toLowerCase()); - // new user gets initially a generated password - newUser.setPassword(encryptedPassword); - newUser.setFirstName(userDTO.getFirstName()); - newUser.setLastName(userDTO.getLastName()); - if (userDTO.getEmail() != null) { - newUser.setEmail(userDTO.getEmail().toLowerCase()); - } - <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeNeo4j) { _%> - newUser.setImageUrl(userDTO.getImageUrl()); - <%_ } _%> - newUser.setLangKey(userDTO.getLangKey()); - // new user is not active - newUser.setActivated(false); - // new user gets registration key - newUser.setActivationKey(RandomUtil.generateActivationKey()); - <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j) { _%> - Set authorities = new HashSet<>(); - authorityRepository.findById(AuthoritiesConstants.USER).ifPresent(authorities::add); - <%_ } else { _%> - Set authorities = new HashSet<>(); - authorities.add(AuthoritiesConstants.USER); - <%_ } _%> - newUser.setAuthorities(authorities); - userRepository.save(newUser); - <%_ if (searchEngineElasticsearch) { _%> - userSearchRepository.save(newUser); - <%_ } _%> - <%_ if (cacheManagerIsAvailable) { _%> - this.clearUserCaches(newUser); - <%_ } _%> - log.debug("Created Information for User: {}", newUser); - return newUser; - <%_ } else { /* reactive */ _%> + <%_ if (reactive) { _%> return userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()) .flatMap(existingUser -> { if (!existingUser.isActivated()) { @@ -379,6 +328,57 @@ public class UserService { <%_ } _%> .doOnNext(user -> log.debug("Created Information for User: {}", user)); }); + <%_ } else { /* !reactive */ _%> + 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(); + } + }); + <%= asEntity('User') %> newUser = new <%= asEntity('User') %>(); + <%_ if (databaseTypeCassandra) { _%> + newUser.setId(UUID.randomUUID().toString()); + <%_ } _%> + String encryptedPassword = passwordEncoder.encode(password); + newUser.setLogin(userDTO.getLogin().toLowerCase()); + // new user gets initially a generated password + newUser.setPassword(encryptedPassword); + newUser.setFirstName(userDTO.getFirstName()); + newUser.setLastName(userDTO.getLastName()); + if (userDTO.getEmail() != null) { + newUser.setEmail(userDTO.getEmail().toLowerCase()); + } + <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeNeo4j) { _%> + newUser.setImageUrl(userDTO.getImageUrl()); + <%_ } _%> + newUser.setLangKey(userDTO.getLangKey()); + // new user is not active + newUser.setActivated(false); + // new user gets registration key + newUser.setActivationKey(RandomUtil.generateActivationKey()); + <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j) { _%> + Set authorities = new HashSet<>(); + authorityRepository.findById(AuthoritiesConstants.USER).ifPresent(authorities::add); + <%_ } else { _%> + Set authorities = new HashSet<>(); + authorities.add(AuthoritiesConstants.USER); + <%_ } _%> + newUser.setAuthorities(authorities); + userRepository.save(newUser); + <%_ if (searchEngineElasticsearch) { _%> + userSearchRepository.save(newUser); + <%_ } _%> + <%_ if (cacheManagerIsAvailable) { _%> + this.clearUserCaches(newUser); + <%_ } _%> + log.debug("Created Information for User: {}", newUser); + return newUser; <%_ } _%> } @@ -418,34 +418,7 @@ public class UserService { } else { user.setLangKey(userDTO.getLangKey()); } - <%_ if (!reactive) { _%> - String encryptedPassword = passwordEncoder.encode(RandomUtil.generatePassword()); - user.setPassword(encryptedPassword); - user.setResetKey(RandomUtil.generateResetKey()); - user.setResetDate(Instant.now()); - user.setActivated(true); - <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j) { _%> - if (userDTO.getAuthorities() != null) { - Set authorities = userDTO.getAuthorities().stream() - .map(authorityRepository::findById) - .filter(Optional::isPresent) - .map(Optional::get) - .collect(Collectors.toSet()); - user.setAuthorities(authorities); - } - <%_ } else { _%> - user.setAuthorities(userDTO.getAuthorities()); - <%_ } _%> - userRepository.save(user); - <%_ if (searchEngineElasticsearch) { _%> - userSearchRepository.save(user); - <%_ } _%> - <%_ if (cacheManagerIsAvailable) { _%> - this.clearUserCaches(user); - <%_ } _%> - log.debug("Created Information for User: {}", user); - return user; - <%_ } else { _%> + <%_ if (reactive) { _%> <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j) { _%> return Flux.fromIterable(userDTO.getAuthorities() != null ? userDTO.getAuthorities() : new HashSet<>()) .flatMap(authorityRepository::findById) @@ -472,6 +445,33 @@ public class UserService { .doOnNext(this::clearUserCaches) <%_ } _%> .doOnNext(user1 -> log.debug("Created Information for User: {}", user1)); + <%_ } else { _%> + String encryptedPassword = passwordEncoder.encode(RandomUtil.generatePassword()); + user.setPassword(encryptedPassword); + user.setResetKey(RandomUtil.generateResetKey()); + user.setResetDate(Instant.now()); + user.setActivated(true); + <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j) { _%> + if (userDTO.getAuthorities() != null) { + Set authorities = userDTO.getAuthorities().stream() + .map(authorityRepository::findById) + .filter(Optional::isPresent) + .map(Optional::get) + .collect(Collectors.toSet()); + user.setAuthorities(authorities); + } + <%_ } else { _%> + user.setAuthorities(userDTO.getAuthorities()); + <%_ } _%> + userRepository.save(user); + <%_ if (searchEngineElasticsearch) { _%> + userSearchRepository.save(user); + <%_ } _%> + <%_ if (cacheManagerIsAvailable) { _%> + this.clearUserCaches(user); + <%_ } _%> + log.debug("Created Information for User: {}", user); + return user; <%_ } _%> } @@ -485,15 +485,15 @@ public class UserService { @Transactional <%_ } _%> public <% if (reactive) { %>Mono<% } else { %>Optional<% } %><<%= asDto('AdminUser') %>> updateUser(<%= asDto('AdminUser') %> userDTO) { - <%_ if (!reactive) { _%> + <%_ if (reactive) { _%> + return userRepository.findById(userDTO.getId()) + .<%_ if (databaseTypeSql || databaseTypeMongodb) { _%>flatMap<% } else { %>map<% } %>(user -> { + <%_ } else { _%> return Optional.of(userRepository .findById(userDTO.getId())) .filter(Optional::isPresent) .map(Optional::get) .map(user -> { - <%_ } else { _%> - return userRepository.findById(userDTO.getId()) - .<%_ if (databaseTypeSql || databaseTypeMongodb) { _%>flatMap<% } else { %>map<% } %>(user -> { <%_ } _%> <%_ if (databaseTypeCouchbase) { _%> if (!user.getLogin().equals(userDTO.getLogin())) { @@ -520,27 +520,7 @@ public class UserService { <%_ } else { /* Cassandra & Couchbase */ _%> user.setAuthorities(userDTO.getAuthorities()); <%_ } _%> - <%_ if (!reactive) { _%> - <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j) { _%> - userDTO.getAuthorities().stream() - .map(authorityRepository::findById) - .filter(Optional::isPresent) - .map(Optional::get) - .forEach(managedAuthorities::add); - <%_ } _%> - <%_ if (databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase || databaseTypeCassandra) { _%> - userRepository.save(user); - <%_ } _%> - <%_ if (searchEngineElasticsearch) { _%> - userSearchRepository.save(user); - <%_ } _%> - <%_ if (cacheManagerIsAvailable) { _%> - this.clearUserCaches(user); - <%_ } _%> - log.debug("Changed Information for User: {}", user); - return user; - }) - <%_ } else { /* reactive */ _%> + <%_ if (reactive) { _%> <%_ if (databaseTypeSql || databaseTypeMongodb) { _%> <%_ if (databaseTypeSql) { _%> return userRepository @@ -564,24 +544,31 @@ public class UserService { .doOnNext(this::clearUserCaches) <%_ } _%> .doOnNext(user -> log.debug("Changed Information for User: {}", user)) - <%_ } _%> - .map(<%= asDto('AdminUser') %>::new); - } - - <%_ if (!reactive) { _%> - public void deleteUser(String login) { - userRepository.findOneByLogin(login).ifPresent(user -> { - userRepository.delete(user); + <%_ } else { /* reactive */ _%> + <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j) { _%> + userDTO.getAuthorities().stream() + .map(authorityRepository::findById) + .filter(Optional::isPresent) + .map(Optional::get) + .forEach(managedAuthorities::add); + <%_ } _%> + <%_ if (databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase || databaseTypeCassandra) { _%> + userRepository.save(user); + <%_ } _%> <%_ if (searchEngineElasticsearch) { _%> - userSearchRepository.delete(user); + userSearchRepository.save(user); <%_ } _%> <%_ if (cacheManagerIsAvailable) { _%> - this.clearUserCaches(user); + this.clearUserCaches(user); <%_ } _%> - log.debug("Deleted User: {}", user); - }); + log.debug("Changed Information for User: {}", user); + return user; + }) + <%_ } _%> + .map(<%= asDto('AdminUser') %>::new); } - <%_ } else { _%> + + <%_ if (reactive) { _%> <%_ if (databaseTypeSql) { _%> @Transactional <%_ } _%> @@ -597,6 +584,19 @@ public class UserService { .doOnNext(user -> log.debug("Deleted User: {}", user)) .then(); } + <%_ } else { _%> + public void deleteUser(String login) { + userRepository.findOneByLogin(login).ifPresent(user -> { + userRepository.delete(user); + <%_ if (searchEngineElasticsearch) { _%> + userSearchRepository.delete(user); + <%_ } _%> + <%_ if (cacheManagerIsAvailable) { _%> + this.clearUserCaches(user); + <%_ } _%> + log.debug("Deleted User: {}", user); + }); + } <%_ } _%> <%_ } /* authenticationType !== 'oauth2'*/ _%> @@ -630,7 +630,18 @@ public class UserService { <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeNeo4j) { _%> user.setImageUrl(imageUrl); <%_ } _%> - <%_ if (!reactive) { _%> + <%_ if (reactive) { _%> + return saveUser(user); + }) + <%_ if (searchEngineElasticsearch) { _%> + .flatMap(user -> userSearchRepository.save(user).thenReturn(user)) + <%_ } _%> + <%_ if (cacheManagerIsAvailable) { _%> + .doOnNext(this::clearUserCaches) + <%_ } _%> + .doOnNext(user -> log.debug("Changed Information for User: {}", user)) + .then(); + <%_ } else { _%> <%_ if (databaseTypeMongodb || databaseTypeCouchbase || databaseTypeNeo4j || databaseTypeCassandra) { _%> userRepository.save(user); <%_ } _%> @@ -642,17 +653,6 @@ public class UserService { <%_ } _%> log.debug("Changed Information for User: {}", user); }); - <%_ } else { _%> - return saveUser(user); - }) - <%_ if (searchEngineElasticsearch) { _%> - .flatMap(user -> userSearchRepository.save(user).thenReturn(user)) - <%_ } _%> - <%_ if (cacheManagerIsAvailable) { _%> - .doOnNext(this::clearUserCaches) - <%_ } _%> - .doOnNext(user -> log.debug("Changed Information for User: {}", user)) - .then(); <%_ } _%> } @@ -724,16 +724,7 @@ public class UserService { } String encryptedPassword = passwordEncoder.encode(newPassword); user.setPassword(encryptedPassword); - <%_ if (!reactive) { _%> - <%_ if (databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase || databaseTypeCassandra) { _%> - userRepository.save(user); - <%_ } _%> - <%_ if (cacheManagerIsAvailable) { _%> - this.clearUserCaches(user); - <%_ } _%> - log.debug("Changed password for User: {}", user); - }); - <%_ } else { _%> + <%_ if (reactive) { _%> return user; }) .flatMap(this::saveUser) @@ -742,6 +733,15 @@ public class UserService { <%_ } _%> .doOnNext(user -> log.debug("Changed password for User: {}", user)) .then(); + <%_ } else { _%> + <%_ if (databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase || databaseTypeCassandra) { _%> + userRepository.save(user); + <%_ } _%> + <%_ if (cacheManagerIsAvailable) { _%> + this.clearUserCaches(user); + <%_ } _%> + log.debug("Changed password for User: {}", user); + }); <%_ } _%> } <%_ } _%> @@ -832,7 +832,9 @@ public class UserService { */ @Scheduled(cron = "0 0 1 * * ?") public void removeNotActivatedUsers() { - <%_ if (!reactive) { _%> + <%_ if (reactive) { _%> + removeNotActivatedUsersReactively().blockLast(); + <%_ } else { _%> userRepository .findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS)) .forEach(user -> { @@ -845,8 +847,6 @@ public class UserService { this.clearUserCaches(user); <%_ } _%> }); - <%_ } else { _%> - removeNotActivatedUsersReactively().blockLast(); } <%_ if (databaseTypeSql) { _%> @@ -883,7 +883,46 @@ public class UserService { private <% if (reactive) { %>Mono<<%= asEntity('User') %>><% } else { %><%= asEntity('User') %><% } %> syncUserWithIdP(Map details, <%= asEntity('User') %> user) { // save authorities in to sync user roles/groups between IdP and JHipster's local database - <%_ if (!reactive) { _%> + <%_ if (reactive) { _%> + Collection userAuthorities = + user.getAuthorities().stream()<% if (!databaseTypeCouchbase) { %>.map(Authority::getName)<% } %>.collect(Collectors.toList()); + + return getAuthorities().collectList() + .flatMapMany(dbAuthorities -> { + List authoritiesToSave = userAuthorities.stream() + .filter(authority -> !dbAuthorities.contains(authority)) + .map(authority -> { + Authority authorityToSave = new Authority(); + authorityToSave.setName(authority); + return authorityToSave; + }) + .collect(Collectors.toList()); + return Flux.fromIterable(authoritiesToSave); + }) + .doOnNext(authority -> log.debug("Saving authority '{}' in local database", authority)) + .flatMap(authorityRepository::save) + .then(userRepository.findOneByLogin(user.getLogin())) + .switchIfEmpty(<% if (authenticationTypeOauth2 && databaseTypeSql) { %>saveUser(user, true)<% } else { %>userRepository.save(user)<% } %>) + .flatMap(existingUser -> { + // if IdP sends last updated information, use it to determine if an update should happen + if (details.get("updated_at") != null) { + Instant dbModifiedDate = existingUser.getLastModifiedDate(); + Instant idpModifiedDate = (Instant) details.get("updated_at"); + if (idpModifiedDate.isAfter(dbModifiedDate)) { + log.debug("Updating user '{}' in local database", user.getLogin()); + return updateUser(user.getFirstName(), user.getLastName(), user.getEmail(), + user.getLangKey(), user.getImageUrl()); + } + // no last updated info, blindly update + } else { + log.debug("Updating user '{}' in local database", user.getLogin()); + return updateUser(user.getFirstName(), user.getLastName(), user.getEmail(), + user.getLangKey(), user.getImageUrl()); + } + return Mono.empty(); + }) + .thenReturn(user); + <%_ } else { _%> Collection dbAuthorities = getAuthorities(); <%_ if (!databaseTypeCouchbase) { _%> Collection userAuthorities = @@ -925,45 +964,6 @@ public class UserService { <%_ } _%> } return user; - <%_ } else { _%> - Collection userAuthorities = - user.getAuthorities().stream()<% if (!databaseTypeCouchbase) { %>.map(Authority::getName)<% } %>.collect(Collectors.toList()); - - return getAuthorities().collectList() - .flatMapMany(dbAuthorities -> { - List authoritiesToSave = userAuthorities.stream() - .filter(authority -> !dbAuthorities.contains(authority)) - .map(authority -> { - Authority authorityToSave = new Authority(); - authorityToSave.setName(authority); - return authorityToSave; - }) - .collect(Collectors.toList()); - return Flux.fromIterable(authoritiesToSave); - }) - .doOnNext(authority -> log.debug("Saving authority '{}' in local database", authority)) - .flatMap(authorityRepository::save) - .then(userRepository.findOneByLogin(user.getLogin())) - .switchIfEmpty(<% if (authenticationTypeOauth2 && databaseTypeSql) { %>saveUser(user, true)<% } else { %>userRepository.save(user)<% } %>) - .flatMap(existingUser -> { - // if IdP sends last updated information, use it to determine if an update should happen - if (details.get("updated_at") != null) { - Instant dbModifiedDate = existingUser.getLastModifiedDate(); - Instant idpModifiedDate = (Instant) details.get("updated_at"); - if (idpModifiedDate.isAfter(dbModifiedDate)) { - log.debug("Updating user '{}' in local database", user.getLogin()); - return updateUser(user.getFirstName(), user.getLastName(), user.getEmail(), - user.getLangKey(), user.getImageUrl()); - } - // no last updated info, blindly update - } else { - log.debug("Updating user '{}' in local database", user.getLogin()); - return updateUser(user.getFirstName(), user.getLastName(), user.getEmail(), - user.getLangKey(), user.getImageUrl()); - } - return Mono.empty(); - }) - .thenReturn(user); <%_ } _%> } <%_ } _%> @@ -982,7 +982,7 @@ public class UserService { <%_ if (databaseTypeSql) { _%> @Transactional <%_ } _%> - public <% if (!reactive) { %><%= asDto('AdminUser') %><% } else { %>Mono<<%= asDto('AdminUser') %>><% } %> getUserFromAuthentication(AbstractAuthenticationToken authToken) { + public <% if (reactive) { %>Mono<<%= asDto('AdminUser') %>><% } else { %><%= asDto('AdminUser') %><% } %> getUserFromAuthentication(AbstractAuthenticationToken authToken) { Map attributes; if (authToken instanceof OAuth2AuthenticationToken) { attributes = ((OAuth2AuthenticationToken) authToken).getPrincipal().getAttributes(); @@ -1006,10 +1006,10 @@ public class UserService { <%_ if (databaseTypeNo) { _%> return <% if (reactive) { %>Mono.just(user)<% } else { %>user<% } %>; <%_ } else { _%> - <%_ if (!reactive) { _%> - return new <%= asDto('AdminUser') %>(syncUserWithIdP(attributes, user)); - <%_ } else { _%> + <%_ if (reactive) { _%> return syncUserWithIdP(attributes, user).flatMap(u -> Mono.just(new <%= asDto('AdminUser') %>(u))); + <%_ } else { _%> + return new <%= asDto('AdminUser') %>(syncUserWithIdP(attributes, user)); <%_ } _%> <%_ } _%> } diff --git a/generators/server/templates/src/main/java/package/web/rest/AccountResource.java.ejs b/generators/server/templates/src/main/java/package/web/rest/AccountResource.java.ejs index 3ead6e88ac6..aba32c28930 100644 --- a/generators/server/templates/src/main/java/package/web/rest/AccountResource.java.ejs +++ b/generators/server/templates/src/main/java/package/web/rest/AccountResource.java.ejs @@ -108,12 +108,12 @@ import com.fasterxml.jackson.annotation.JsonCreator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.GrantedAuthority; - <%_ if (!reactive) { _%> -import org.springframework.security.core.context.SecurityContextHolder; - <%_ } else { _%> + <%_ if (reactive) { _%> import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.userdetails.UserDetails; + <%_ } else { _%> +import org.springframework.security.core.context.SecurityContextHolder; <%_ } _%> import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @@ -145,15 +145,7 @@ public class AccountResource { * @throws AccountResourceException {@code 500 (Internal Server Error)} if the user couldn't be returned. */ @GetMapping("/account") - <%_ if (!reactive) { _%> - public UserVM getAccount() { - String login = SecurityUtils.getCurrentUserLogin() - .orElseThrow(AccountResourceException::new); - Set authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities().stream() - .map(GrantedAuthority::getAuthority) - .collect(Collectors.toSet()); - return new UserVM(login, authorities); - <%_ } else { _%> + <%_ if (reactive) { _%> public Mono getAccount() { return ReactiveSecurityContextHolder.getContext() .map(SecurityContext::getAuthentication) @@ -172,6 +164,14 @@ public class AccountResource { return new UserVM(login, authorities); }) .switchIfEmpty(Mono.error(new AccountResourceException())); + <%_ } else { _%> + public UserVM getAccount() { + String login = SecurityUtils.getCurrentUserLogin() + .orElseThrow(AccountResourceException::new); + Set authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities().stream() + .map(GrantedAuthority::getAuthority) + .collect(Collectors.toSet()); + return new UserVM(login, authorities); <%_ } _%> } @@ -309,13 +309,13 @@ public class AccountResource { if (isPasswordLengthInvalid(managedUserVM.getPassword())) { throw new InvalidPasswordException(); } - <%_ if (!reactive) { _%> - <%= asEntity('User') %> user = userService.registerUser(managedUserVM, managedUserVM.getPassword()); - mailService.sendActivationEmail(user); - <%_ } else { _%> + <%_ if (reactive) { _%> return userService.registerUser(managedUserVM, managedUserVM.getPassword()) .doOnSuccess(mailService::sendActivationEmail) .then(); + <%_ } else { _%> + <%= asEntity('User') %> user = userService.registerUser(managedUserVM, managedUserVM.getPassword()); + mailService.sendActivationEmail(user); <%_ } _%> } @@ -327,15 +327,15 @@ public class AccountResource { */ @GetMapping("/activate") public <% if (reactive) { %>Mono<% } else { %>void<% } %> activateAccount(@RequestParam(value = "key") String key) { - <%_ if (!reactive) { _%> + <%_ if (reactive) { _%> + return userService.activateRegistration(key) + .switchIfEmpty(Mono.error(new AccountResourceException("No user was found for this activation key"))) + .then(); + <%_ } else { _%> Optional<<%= asEntity('User') %>> user = userService.activateRegistration(key); if (!user.isPresent()) { throw new AccountResourceException("No user was found for this activation key"); } - <%_ } else { _%> - return userService.activateRegistration(key) - .switchIfEmpty(Mono.error(new AccountResourceException("No user was found for this activation key"))) - .then(); <%_ } _%> } @@ -346,14 +346,14 @@ public class AccountResource { * @return the login if the user is authenticated. */ @GetMapping("/authenticate") - <%_ if (!reactive) { _%> - public String isAuthenticated(HttpServletRequest request) { - log.debug("REST request to check if the current user is authenticated"); - return request.getRemoteUser(); - <%_ } else { _%> + <%_ if (reactive) { _%> public Mono isAuthenticated(ServerWebExchange request) { log.debug("REST request to check if the current user is authenticated"); return request.getPrincipal().map(Principal::getName); + <%_ } else { _%> + public String isAuthenticated(HttpServletRequest request) { + log.debug("REST request to check if the current user is authenticated"); + return request.getRemoteUser(); <%_ } _%> } @@ -367,10 +367,10 @@ public class AccountResource { public <% if (reactive) { %>Mono<<%= asDto('AdminUser') %>><% } else { %><%= asDto('AdminUser') %><% } %> getAccount() { return userService.getUserWithAuthorities() .map(<%= asDto('AdminUser') %>::new) - <%_ if (!reactive) { _%> - .orElseThrow(() -> new AccountResourceException("User could not be found")); - <%_ } else { _%> + <%_ if (reactive) { _%> .switchIfEmpty(Mono.error(new AccountResourceException("User could not be found"))); + <%_ } else { _%> + .orElseThrow(() -> new AccountResourceException("User could not be found")); <%_ } _%> } @@ -382,20 +382,7 @@ public class AccountResource { * @throws RuntimeException {@code 500 (Internal Server Error)} if the user login wasn't found. */ @PostMapping("/account") - <%_ if (!reactive) { _%> - public void saveAccount(@Valid @RequestBody <%= asDto('AdminUser') %> userDTO) { - String userLogin = SecurityUtils.getCurrentUserLogin().orElseThrow(() -> new AccountResourceException("Current user login not found")); - Optional<<%= asEntity('User') %>> existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()); - if (existingUser.isPresent() && (!existingUser.get().getLogin().equalsIgnoreCase(userLogin))) { - throw new EmailAlreadyUsedException(); - } - Optional<<%= asEntity('User') %>> user = userRepository.findOneByLogin(userLogin); - if (!user.isPresent()) { - throw new AccountResourceException("User could not be found"); - } - userService.updateUser(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail(), - userDTO.getLangKey()<% if (databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeNeo4j) { %>, userDTO.getImageUrl()<% } %>); - <%_ } else { _%> + <%_ if (reactive) { _%> public Mono saveAccount(@Valid @RequestBody <%= asDto('AdminUser') %> userDTO) { return SecurityUtils.getCurrentUserLogin() .switchIfEmpty(Mono.error(new AccountResourceException("Current user login not found"))) @@ -411,6 +398,19 @@ public class AccountResource { .switchIfEmpty(Mono.error(new AccountResourceException("User could not be found"))) .flatMap(user -> userService.updateUser(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail(), userDTO.getLangKey()<% if (databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeNeo4j) { %>, userDTO.getImageUrl()<% } %>)); + <%_ } else { _%> + public void saveAccount(@Valid @RequestBody <%= asDto('AdminUser') %> userDTO) { + String userLogin = SecurityUtils.getCurrentUserLogin().orElseThrow(() -> new AccountResourceException("Current user login not found")); + Optional<<%= asEntity('User') %>> existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()); + if (existingUser.isPresent() && (!existingUser.get().getLogin().equalsIgnoreCase(userLogin))) { + throw new EmailAlreadyUsedException(); + } + Optional<<%= asEntity('User') %>> user = userRepository.findOneByLogin(userLogin); + if (!user.isPresent()) { + throw new AccountResourceException("User could not be found"); + } + userService.updateUser(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail(), + userDTO.getLangKey()<% if (databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeNeo4j) { %>, userDTO.getImageUrl()<% } %>); <%_ } _%> } @@ -484,17 +484,7 @@ public class AccountResource { * @param mail the mail of the user. */ @PostMapping(path = "/account/reset-password/init") - <%_ if (!reactive) { _%> - public void requestPasswordReset(@RequestBody String mail) { - Optional<<%= asEntity('User') %>> user = userService.requestPasswordReset(mail); - if (user.isPresent()) { - mailService.sendPasswordResetMail(user.get()); - } else { - // Pretend the request has been successful to prevent checking which emails really exist - // but log that an invalid attempt has been made - log.warn("Password reset requested for non existing mail"); - } - <%_ } else { _%> + <%_ if (reactive) { _%> public Mono requestPasswordReset(@RequestBody String mail) { return userService.requestPasswordReset(mail) .doOnSuccess(user -> { @@ -507,6 +497,16 @@ public class AccountResource { } }) .then(); + <%_ } else { _%> + public void requestPasswordReset(@RequestBody String mail) { + Optional<<%= asEntity('User') %>> user = userService.requestPasswordReset(mail); + if (user.isPresent()) { + mailService.sendPasswordResetMail(user.get()); + } else { + // Pretend the request has been successful to prevent checking which emails really exist + // but log that an invalid attempt has been made + log.warn("Password reset requested for non existing mail"); + } <%_ } _%> } @@ -522,7 +522,7 @@ public class AccountResource { if (isPasswordLengthInvalid(keyAndPassword.getNewPassword())) { throw new InvalidPasswordException(); } - <%_ if (!reactive) { _%> + <%_ if (reactive) { _%> Optional<<%= asEntity('User') %>> user = userService.completePasswordReset(keyAndPassword.getNewPassword(), keyAndPassword.getKey()); diff --git a/generators/server/templates/src/main/java/package/web/rest/KafkaResource.java.ejs b/generators/server/templates/src/main/java/package/web/rest/KafkaResource.java.ejs index 04fdff7ca33..85b3b711958 100644 --- a/generators/server/templates/src/main/java/package/web/rest/KafkaResource.java.ejs +++ b/generators/server/templates/src/main/java/package/web/rest/KafkaResource.java.ejs @@ -63,45 +63,51 @@ public class <%= upperFirstCamelCase(baseName) %>KafkaResource { private final Logger log = LoggerFactory.getLogger(<%= upperFirstCamelCase(baseName) %>KafkaResource.class); private final KafkaProperties kafkaProperties; -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + private KafkaSender sender; +<%_ } else { _%> private KafkaProducer producer; private ExecutorService sseExecutorService = Executors.newCachedThreadPool(); -<%_ } else { _%> - private KafkaSender sender; <%_ } _%> public <%= upperFirstCamelCase(baseName) %>KafkaResource(KafkaProperties kafkaProperties) { this.kafkaProperties = kafkaProperties; -<%_ if (!reactive) { _%> - this.producer = new KafkaProducer<>(kafkaProperties.getProducerProps()); -<%_ } else { _%> +<%_ if (reactive) { _%> this.sender = KafkaSender.create(SenderOptions.create(kafkaProperties.getProducerProps())); +<%_ } else { _%> + this.producer = new KafkaProducer<>(kafkaProperties.getProducerProps()); <%_ } _%> } @PostMapping("/publish/{topic}") - public <% if (!reactive) { %>PublishResult<% } else { %>Mono<% } %> publish(@PathVariable String topic, @RequestParam String message, @RequestParam(required = false) String key)<% if (!reactive) { %> throws ExecutionException, InterruptedException<% } %> { + public <% if (reactive) { %>Mono<% } else { %>PublishResult<% } %> publish(@PathVariable String topic, @RequestParam String message, @RequestParam(required = false) String key)<% if (!reactive) { %> throws ExecutionException, InterruptedException<% } %> { log.debug("REST request to send to Kafka topic {} with key {} the message : {}", topic, key, message); -<%_ if (!reactive) { _%> - RecordMetadata metadata = producer.send(new ProducerRecord<>(topic, key, message)).get(); - return new PublishResult(metadata.topic(), metadata.partition(), metadata.offset(), Instant.ofEpochMilli(metadata.timestamp())); -<%_ } else { _%> +<%_ if (reactive) { _%> return Mono.just(SenderRecord.create(topic, null, null, key, message, null)) .as(sender::send) .next() .map(SenderResult::recordMetadata) .map(metadata -> new PublishResult(metadata.topic(), metadata.partition(), metadata.offset(), Instant.ofEpochMilli(metadata.timestamp()))); +<%_ } else { _%> + RecordMetadata metadata = producer.send(new ProducerRecord<>(topic, key, message)).get(); + return new PublishResult(metadata.topic(), metadata.partition(), metadata.offset(), Instant.ofEpochMilli(metadata.timestamp())); <%_ } _%> } @GetMapping("/consume") - public <% if (!reactive) { %>SseEmitter<% } else { %>Flux<% } %> consume(@RequestParam("topic") List topics, @RequestParam Map consumerParams) { + public <% if (reactive) { %>Flux<% } else { %>SseEmitter<% } %> consume(@RequestParam("topic") List topics, @RequestParam Map consumerParams) { log.debug("REST request to consume records from Kafka topics {}", topics); Map consumerProps = kafkaProperties.getConsumerProps(); consumerProps.putAll(consumerParams); consumerProps.remove("topic"); -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + ReceiverOptions receiverOptions = ReceiverOptions.create(consumerProps) + .subscription(topics); + return KafkaReceiver.create(receiverOptions) + .receive() + .map(ConsumerRecord::value); +<%_ } else { _%> SseEmitter emitter = new SseEmitter(0L); sseExecutorService.execute(() -> { KafkaConsumer consumer = new KafkaConsumer<>(consumerProps); @@ -125,12 +131,6 @@ public class <%= upperFirstCamelCase(baseName) %>KafkaResource { emitter.complete(); }); return emitter; -<%_ } else { _%> - ReceiverOptions receiverOptions = ReceiverOptions.create(consumerProps) - .subscription(topics); - return KafkaReceiver.create(receiverOptions) - .receive() - .map(ConsumerRecord::value); <%_ } _%> } diff --git a/generators/server/templates/src/main/java/package/web/rest/LogoutResource.java.ejs b/generators/server/templates/src/main/java/package/web/rest/LogoutResource.java.ejs index ef0d34b42c1..fb34c2919a5 100644 --- a/generators/server/templates/src/main/java/package/web/rest/LogoutResource.java.ejs +++ b/generators/server/templates/src/main/java/package/web/rest/LogoutResource.java.ejs @@ -25,13 +25,13 @@ import org.springframework.security.oauth2.client.registration.<% if (reactive) import org.springframework.security.oauth2.core.oidc.OidcIdToken; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; -<%_ if (!reactive) { _%> -import javax.servlet.http.HttpServletRequest; -import org.springframework.http.HttpHeaders; -<%_ } else { _%> +<%_ if (reactive) { _%> import org.springframework.web.server.WebSession; import org.springframework.http.server.reactive.ServerHttpRequest; import reactor.core.publisher.Mono; +<%_ } else { _%> +import javax.servlet.http.HttpServletRequest; +import org.springframework.http.HttpHeaders; <%_ } _%> import java.util.Map; @@ -60,63 +60,63 @@ public class LogoutResource { * @return the {@link ResponseEntity} with status {@code 200 (OK)} and a body with a global logout URL. */ @PostMapping("/api/logout") -<%_ if (!reactive) { _%> - public ResponseEntity logout(HttpServletRequest request, - @AuthenticationPrincipal(expression = "idToken") OidcIdToken idToken) { - StringBuilder logoutUrl = new StringBuilder(); +<%_ if (reactive) { _%> + public Mono> logout(@AuthenticationPrincipal(expression = "idToken") OidcIdToken idToken, ServerHttpRequest request, WebSession session) { + return session + .invalidate() + .then( + this.registration.map(oidc -> prepareLogoutUri(request, oidc, idToken)) + ); + } - String issuerUri = this.registration.getProviderDetails().getIssuerUri(); + private Map prepareLogoutUri(ServerHttpRequest request, ClientRegistration clientRegistration, OidcIdToken idToken) { + StringBuilder logoutUrl = new StringBuilder(); + String issuerUri = clientRegistration.getProviderDetails().getIssuerUri(); if (issuerUri.contains("auth0.com")) { logoutUrl.append(issuerUri.endsWith("/") ? issuerUri + "v2/logout" : issuerUri + "/v2/logout"); } else { - logoutUrl.append(this.registration.getProviderDetails().getConfigurationMetadata().get("end_session_endpoint").toString()); + logoutUrl.append(clientRegistration.getProviderDetails().getConfigurationMetadata().get("end_session_endpoint").toString()); } - String originUrl = request.getHeader(HttpHeaders.ORIGIN); - + String originUrl = request.getHeaders().getOrigin(); if (logoutUrl.indexOf("/protocol") > -1) { logoutUrl.append("?redirect_uri=").append(originUrl); } else if (logoutUrl.indexOf("auth0.com") > -1) { // Auth0 - logoutUrl.append("?client_id=").append(this.registration.getClientId()).append("&returnTo=").append(originUrl); + logoutUrl.append("?client_id=").append(clientRegistration.getClientId()).append("&returnTo=").append(originUrl); } else { // Okta logoutUrl.append("?id_token_hint=").append(idToken.getTokenValue()).append("&post_logout_redirect_uri=").append(originUrl); } - - request.getSession().invalidate(); - return ResponseEntity.ok().body(Map.of("logoutUrl", logoutUrl.toString())); + return Map.of("logoutUrl", logoutUrl.toString()); } <%_ } else { _%> - public Mono> logout(@AuthenticationPrincipal(expression = "idToken") OidcIdToken idToken, ServerHttpRequest request, WebSession session) { - return session - .invalidate() - .then( - this.registration.map(oidc -> prepareLogoutUri(request, oidc, idToken)) - ); - } - - private Map prepareLogoutUri(ServerHttpRequest request, ClientRegistration clientRegistration, OidcIdToken idToken) { + public ResponseEntity logout(HttpServletRequest request, + @AuthenticationPrincipal(expression = "idToken") OidcIdToken idToken) { StringBuilder logoutUrl = new StringBuilder(); - String issuerUri = clientRegistration.getProviderDetails().getIssuerUri(); + + String issuerUri = this.registration.getProviderDetails().getIssuerUri(); if (issuerUri.contains("auth0.com")) { logoutUrl.append(issuerUri.endsWith("/") ? issuerUri + "v2/logout" : issuerUri + "/v2/logout"); } else { - logoutUrl.append(clientRegistration.getProviderDetails().getConfigurationMetadata().get("end_session_endpoint").toString()); + logoutUrl.append(this.registration.getProviderDetails().getConfigurationMetadata().get("end_session_endpoint").toString()); } - String originUrl = request.getHeaders().getOrigin(); + String originUrl = request.getHeader(HttpHeaders.ORIGIN); + if (logoutUrl.indexOf("/protocol") > -1) { logoutUrl.append("?redirect_uri=").append(originUrl); } else if (logoutUrl.indexOf("auth0.com") > -1) { // Auth0 - logoutUrl.append("?client_id=").append(clientRegistration.getClientId()).append("&returnTo=").append(originUrl); + logoutUrl.append("?client_id=").append(this.registration.getClientId()).append("&returnTo=").append(originUrl); } else { // Okta logoutUrl.append("?id_token_hint=").append(idToken.getTokenValue()).append("&post_logout_redirect_uri=").append(originUrl); } - return Map.of("logoutUrl", logoutUrl.toString()); - } + request.getSession().invalidate(); + return ResponseEntity.ok().body(Map.of("logoutUrl", logoutUrl.toString())); + } <%_ } _%> + } diff --git a/generators/server/templates/src/main/java/package/web/rest/PublicUserResource.java.ejs b/generators/server/templates/src/main/java/package/web/rest/PublicUserResource.java.ejs index ee24e05b80a..e38eebd81aa 100644 --- a/generators/server/templates/src/main/java/package/web/rest/PublicUserResource.java.ejs +++ b/generators/server/templates/src/main/java/package/web/rest/PublicUserResource.java.ejs @@ -42,10 +42,10 @@ import tech.jhipster.web.util.PaginationUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) { _%> - <%_ if (!reactive) { _%> -import org.springframework.data.domain.Page; - <%_ } else { _%> + <%_ if (reactive) { _%> import org.springframework.data.domain.PageImpl; + <%_ } else { _%> +import org.springframework.data.domain.Page; <%_ } _%> import org.springframework.data.domain.Pageable; <%_ if (!reactive) { _%> @@ -58,23 +58,21 @@ import org.springframework.http.ResponseEntity; import org.springframework.http.server.reactive.ServerHttpRequest; <%_ } _%> import org.springframework.web.bind.annotation.*; -<%_ if (!reactive) { _%> -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; -<%_ } _%> <%_ if (reactive) { _%> import org.springframework.web.server.ResponseStatusException; import org.springframework.web.util.UriComponentsBuilder; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +<%_ } else {_%> +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; <%_ } _%> <%_ if (!reactive) { _%> -import java.util.*; -<%_ } _%> -<%_ if (reactive) { _%> import java.util.ArrayList; import java.util.List; import java.util.Arrays; +<%_ } else { _%> +import java.util.*; <%_ } _%> <%_ if (searchEngineElasticsearch && !reactive) { _%> import java.util.stream.Collectors; @@ -125,32 +123,32 @@ public class PublicUserResource { */ @GetMapping("/users") <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) { _%> - <%_ if (!reactive) { _%> - public ResponseEntity>> getAllPublicUsers(@org.springdoc.api.annotations.ParameterObject Pageable pageable) { + <%_ if (reactive) { _%> + public Mono>>> getAllPublicUsers(ServerHttpRequest request, @org.springdoc.api.annotations.ParameterObject Pageable pageable) { log.debug("REST request to get all public User names"); <%_ if (!authenticationTypeOauth2) { _%> if (!onlyContainsAllowedProperties(pageable)) { - return ResponseEntity.badRequest().build(); + return Mono.just(ResponseEntity.badRequest().build()); } <%_ } _%> - final Page<<%= asDto('User') %>> page = userService.getAllPublicUsers(pageable); - HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); - return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); + return userService.countManagedUsers() + .map(total -> new PageImpl<>(new ArrayList<>(), pageable, total)) + .map(page -> PaginationUtil.generatePaginationHttpHeaders(UriComponentsBuilder.fromHttpRequest(request), page)) + .map(headers -> ResponseEntity.ok().headers(headers).body(userService.getAllPublicUsers(pageable))); } <%_ } else { _%> - public Mono>>> getAllPublicUsers(ServerHttpRequest request, @org.springdoc.api.annotations.ParameterObject Pageable pageable) { + public ResponseEntity>> getAllPublicUsers(@org.springdoc.api.annotations.ParameterObject Pageable pageable) { log.debug("REST request to get all public User names"); <%_ if (!authenticationTypeOauth2) { _%> if (!onlyContainsAllowedProperties(pageable)) { - return Mono.just(ResponseEntity.badRequest().build()); + return ResponseEntity.badRequest().build(); } <%_ } _%> - return userService.countManagedUsers() - .map(total -> new PageImpl<>(new ArrayList<>(), pageable, total)) - .map(page -> PaginationUtil.generatePaginationHttpHeaders(UriComponentsBuilder.fromHttpRequest(request), page)) - .map(headers -> ResponseEntity.ok().headers(headers).body(userService.getAllPublicUsers(pageable))); + final Page<<%= asDto('User') %>> page = userService.getAllPublicUsers(pageable); + HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); + return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); } <%_ } _%> <%_ if (!authenticationTypeOauth2) { _%> @@ -186,16 +184,16 @@ public class PublicUserResource { @GetMapping("/_search/users/{query}") public <% if(reactive) { %>Mono<<% } %>List<<%= asDto('User') %>><% if(reactive) { %>><% } %> search(@PathVariable String query) { <%_ if (searchEngineElasticsearch) { _%> - <%_ if (!reactive) { _%> + <%_ if (reactive) { _%> + return userSearchRepository.search(query).map(<%= asDto('User') %>::new).collectList(); + <%_ } else { _%> return StreamSupport .stream(userSearchRepository.search(query).spliterator(), false) .map(<%= asDto('User') %>::new) .collect(Collectors.toList()); - <%_ } else { _%> - return userSearchRepository.search(query).map(<%= asDto('User') %>::new).collectList(); <%_ } _%> <%_ } else { _%> - <%_ if (!reactive) { _%> + <%_ if (reactive) { _%> return StreamSupport .stream(userRepository.search(User.PREFIX, query).spliterator(), false) .map(<%= asDto('User') %>::new) diff --git a/generators/server/templates/src/main/java/package/web/rest/UserJWTController.java.ejs b/generators/server/templates/src/main/java/package/web/rest/UserJWTController.java.ejs index 33f6f1c13fd..33c2412d974 100644 --- a/generators/server/templates/src/main/java/package/web/rest/UserJWTController.java.ejs +++ b/generators/server/templates/src/main/java/package/web/rest/UserJWTController.java.ejs @@ -51,30 +51,7 @@ import javax.validation.Valid; @RequestMapping("/api") public class UserJWTController { -<%_ if (!reactive) { _%> - private final TokenProvider tokenProvider; - - private final AuthenticationManagerBuilder authenticationManagerBuilder; - - public UserJWTController(TokenProvider tokenProvider, AuthenticationManagerBuilder authenticationManagerBuilder) { - this.tokenProvider = tokenProvider; - this.authenticationManagerBuilder = authenticationManagerBuilder; - } - - @PostMapping("/authenticate") - public ResponseEntity authorize(@Valid @RequestBody LoginVM loginVM) { - - UsernamePasswordAuthenticationToken authenticationToken = - new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword()); - - Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken); - SecurityContextHolder.getContext().setAuthentication(authentication); - String jwt = tokenProvider.createToken(authentication, loginVM.isRememberMe()); - HttpHeaders httpHeaders = new HttpHeaders(); - httpHeaders.add(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt); - return new ResponseEntity<>(new JWTToken(jwt), httpHeaders, HttpStatus.OK); - } -<%_ } else { _%> +<%_ if (reactive) { _%> private final TokenProvider tokenProvider; private final ReactiveAuthenticationManager authenticationManager; @@ -97,8 +74,31 @@ public class UserJWTController { return new ResponseEntity<>(new JWTToken(jwt), httpHeaders, HttpStatus.OK); }); } +<%_ } else { _%> + private final TokenProvider tokenProvider; + + private final AuthenticationManagerBuilder authenticationManagerBuilder; + + public UserJWTController(TokenProvider tokenProvider, AuthenticationManagerBuilder authenticationManagerBuilder) { + this.tokenProvider = tokenProvider; + this.authenticationManagerBuilder = authenticationManagerBuilder; + } + + @PostMapping("/authenticate") + public ResponseEntity authorize(@Valid @RequestBody LoginVM loginVM) { + + UsernamePasswordAuthenticationToken authenticationToken = + new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword()); + Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken); + SecurityContextHolder.getContext().setAuthentication(authentication); + String jwt = tokenProvider.createToken(authentication, loginVM.isRememberMe()); + HttpHeaders httpHeaders = new HttpHeaders(); + 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/generators/server/templates/src/main/java/package/web/rest/UserResource.java.ejs b/generators/server/templates/src/main/java/package/web/rest/UserResource.java.ejs index 31c217c418d..8c0c05d667d 100644 --- a/generators/server/templates/src/main/java/package/web/rest/UserResource.java.ejs +++ b/generators/server/templates/src/main/java/package/web/rest/UserResource.java.ejs @@ -51,10 +51,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) { _%> - <%_ if (!reactive) { _%> -import org.springframework.data.domain.Page; - <%_ } else { _%> + <%_ if (reactive) { _%> import org.springframework.data.domain.PageImpl; + <%_ } else { _%> +import org.springframework.data.domain.Page; <%_ } _%> import org.springframework.data.domain.Pageable; <%_ if (!reactive) { _%> @@ -68,14 +68,13 @@ import org.springframework.http.server.reactive.ServerHttpRequest; <%_ } _%> import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; -<%_ if (!reactive) { _%> -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; -<%_ } _%> <%_ if (reactive) { _%> import org.springframework.web.server.ResponseStatusException; import org.springframework.web.util.UriComponentsBuilder; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +<%_ } else { _%> +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; <%_ } _%> import javax.validation.constraints.Pattern; @@ -175,19 +174,7 @@ public class UserResource { if (userDTO.getId() != null) { throw new BadRequestAlertException("A new user cannot already have an ID", "userManagement", "idexists"); // Lowercase the user login before comparing with database - <%_ if (!reactive) { _%> - } else if (userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()).isPresent()) { - throw new LoginAlreadyUsedException(); - } else if (userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()).isPresent()) { - throw new EmailAlreadyUsedException(); - } else { - <%= asEntity('User') %> newUser = userService.createUser(userDTO); - mailService.sendCreationEmail(newUser); - return ResponseEntity.created(new URI("/api/admin/users/" + newUser.getLogin())) - .headers(HeaderUtil.createAlert(applicationName, <% if (enableTranslation) { %> "userManagement.created"<% } else { %> "A user is created with identifier " + newUser.getLogin()<% } %>, newUser.getLogin())) - .body(newUser); - } - <%_ } else { _%> + <%_ if (reactive) { _%> } return userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()) .hasElement() @@ -214,6 +201,18 @@ public class UserResource { throw new RuntimeException(e); } }); + <%_ } else { _%> + } else if (userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()).isPresent()) { + throw new LoginAlreadyUsedException(); + } else if (userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()).isPresent()) { + throw new EmailAlreadyUsedException(); + } else { + <%= asEntity('User') %> newUser = userService.createUser(userDTO); + mailService.sendCreationEmail(newUser); + return ResponseEntity.created(new URI("/api/admin/users/" + newUser.getLogin())) + .headers(HeaderUtil.createAlert(applicationName, <% if (enableTranslation) { %> "userManagement.created"<% } else { %> "A user is created with identifier " + newUser.getLogin()<% } %>, newUser.getLogin())) + .body(newUser); + } <%_ } _%> } @@ -227,22 +226,7 @@ public class UserResource { */ @PutMapping("/users") @PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")") - <%_ if (!reactive) { _%> - public ResponseEntity<<%= asDto('AdminUser') %>> updateUser(@Valid @RequestBody <%= asDto('AdminUser') %> userDTO) { - log.debug("REST request to update User : {}", userDTO); - Optional<<%= asEntity('User') %>> existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()); - if (existingUser.isPresent() && (!existingUser.get().getId().equals(userDTO.getId()))) { - throw new EmailAlreadyUsedException(); - } - existingUser = userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()); - if (existingUser.isPresent() && (!existingUser.get().getId().equals(userDTO.getId()))) { - throw new LoginAlreadyUsedException(); - } - Optional<<%= asDto('AdminUser') %>> updatedUser = userService.updateUser(userDTO); - - return ResponseUtil.wrapOrNotFound(updatedUser, - HeaderUtil.createAlert(applicationName, <% if (enableTranslation) { %>"userManagement.updated"<% } else { %>"A user is updated with identifier " + userDTO.getLogin()<% } %>, userDTO.getLogin())); - <%_ } else { _%> + <%_ if (reactive) { _%> public Mono>> updateUser(@Valid @RequestBody <%= asDto('AdminUser') %> userDTO) { log.debug("REST request to update User : {}", userDTO); return userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()) @@ -267,6 +251,21 @@ public class UserResource { .headers(HeaderUtil.createAlert(applicationName, "userManagement.updated", userDTO.getLogin())) .body(user) ); + <%_ } else { _%> + public ResponseEntity<<%= asDto('AdminUser') %>> updateUser(@Valid @RequestBody <%= asDto('AdminUser') %> userDTO) { + log.debug("REST request to update User : {}", userDTO); + Optional<<%= asEntity('User') %>> existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()); + if (existingUser.isPresent() && (!existingUser.get().getId().equals(userDTO.getId()))) { + throw new EmailAlreadyUsedException(); + } + existingUser = userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()); + if (existingUser.isPresent() && (!existingUser.get().getId().equals(userDTO.getId()))) { + throw new LoginAlreadyUsedException(); + } + Optional<<%= asDto('AdminUser') %>> updatedUser = userService.updateUser(userDTO); + + return ResponseUtil.wrapOrNotFound(updatedUser, + HeaderUtil.createAlert(applicationName, <% if (enableTranslation) { %>"userManagement.updated"<% } else { %>"A user is updated with identifier " + userDTO.getLogin()<% } %>, userDTO.getLogin())); <%_ } _%> } @@ -283,31 +282,31 @@ public class UserResource { @GetMapping("/users") @PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")") <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) { _%> - <%_ if (!reactive) { _%> - public ResponseEntity>> getAllUsers(@org.springdoc.api.annotations.ParameterObject Pageable pageable) { + <%_ if (reactive) { _%> + public Mono>>> getAllUsers(@org.springdoc.api.annotations.ParameterObject ServerHttpRequest request, @org.springdoc.api.annotations.ParameterObject Pageable pageable) { log.debug("REST request to get all User for an admin"); <%_ if (!authenticationTypeOauth2) { _%> if (!onlyContainsAllowedProperties(pageable)) { - return ResponseEntity.badRequest().build(); + return Mono.just(ResponseEntity.badRequest().build()); } <%_ } _%> - final Page<<%= asDto('AdminUser') %>> page = userService.getAllManagedUsers(pageable); - HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); - return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); + return userService.countManagedUsers() + .map(total -> new PageImpl<>(new ArrayList<>(), pageable, total)) + .map(page -> PaginationUtil.generatePaginationHttpHeaders(UriComponentsBuilder.fromHttpRequest(request), page)) + .map(headers -> ResponseEntity.ok().headers(headers).body(userService.getAllManagedUsers(pageable))); <%_ } else { _%> - public Mono>>> getAllUsers(@org.springdoc.api.annotations.ParameterObject ServerHttpRequest request, @org.springdoc.api.annotations.ParameterObject Pageable pageable) { + public ResponseEntity>> getAllUsers(@org.springdoc.api.annotations.ParameterObject Pageable pageable) { log.debug("REST request to get all User for an admin"); <%_ if (!authenticationTypeOauth2) { _%> if (!onlyContainsAllowedProperties(pageable)) { - return Mono.just(ResponseEntity.badRequest().build()); + return ResponseEntity.badRequest().build(); } <%_ } _%> - return userService.countManagedUsers() - .map(total -> new PageImpl<>(new ArrayList<>(), pageable, total)) - .map(page -> PaginationUtil.generatePaginationHttpHeaders(UriComponentsBuilder.fromHttpRequest(request), page)) - .map(headers -> ResponseEntity.ok().headers(headers).body(userService.getAllManagedUsers(pageable))); + final Page<<%= asDto('AdminUser') %>> page = userService.getAllManagedUsers(pageable); + HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); + return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); <%_ } _%> } @@ -333,18 +332,18 @@ public class UserResource { */ @GetMapping("/users/{login}") @PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")") -<%_ if (!reactive) { _%> - public ResponseEntity<<%= asDto('AdminUser') %>> getUser(@PathVariable @Pattern(regexp = Constants.LOGIN_REGEX) String login) { - log.debug("REST request to get User : {}", login); - return ResponseUtil.wrapOrNotFound( - userService.getUserWithAuthoritiesByLogin(login) - .map(<%= asDto('AdminUser') %>::new)); -<%_ } else { _%> +<%_ if (reactive) { _%> public Mono<<%= asDto('AdminUser') %>> getUser(@PathVariable String login) { log.debug("REST request to get User : {}", login); return userService.getUserWithAuthoritiesByLogin(login) .map(<%= asDto('AdminUser') %>::new) .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND))); +<%_ } else { _%> + public ResponseEntity<<%= asDto('AdminUser') %>> getUser(@PathVariable @Pattern(regexp = Constants.LOGIN_REGEX) String login) { + log.debug("REST request to get User : {}", login); + return ResponseUtil.wrapOrNotFound( + userService.getUserWithAuthoritiesByLogin(login) + .map(<%= asDto('AdminUser') %>::new)); <%_ } _%> } <%_ if (!authenticationTypeOauth2) { _%> @@ -357,17 +356,17 @@ public class UserResource { */ @DeleteMapping("/users/{login}") @PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")") - <%_ if (!reactive) { _%> - public ResponseEntity deleteUser(@PathVariable @Pattern(regexp = Constants.LOGIN_REGEX) String login) { - log.debug("REST request to delete User: {}", login); - userService.deleteUser(login); - return ResponseEntity.noContent().headers(HeaderUtil.createAlert(applicationName, <% if (enableTranslation) { %> "userManagement.deleted"<% } else { %> "A user is deleted with identifier " + login<% } %>, login)).build(); - <%_ } else { _%> + <%_ if (reactive) { _%> @ResponseStatus(code = HttpStatus.NO_CONTENT) public Mono> deleteUser(@PathVariable @Pattern(regexp = Constants.LOGIN_REGEX) String login) { log.debug("REST request to delete User: {}", login); return userService.deleteUser(login) .map(it -> ResponseEntity.noContent().headers(HeaderUtil.createAlert( applicationName, "userManagement.deleted", login)).build()); + <%_ } else { _%> + public ResponseEntity deleteUser(@PathVariable @Pattern(regexp = Constants.LOGIN_REGEX) String login) { + log.debug("REST request to delete User: {}", login); + userService.deleteUser(login); + return ResponseEntity.noContent().headers(HeaderUtil.createAlert(applicationName, <% if (enableTranslation) { %> "userManagement.deleted"<% } else { %> "A user is deleted with identifier " + login<% } %>, login)).build(); <%_ } _%> } <%_ } _%> diff --git a/generators/server/templates/src/main/java/package/web/rest/errors/ExceptionTranslator.java.ejs b/generators/server/templates/src/main/java/package/web/rest/errors/ExceptionTranslator.java.ejs index 62430894613..411f7387f13 100644 --- a/generators/server/templates/src/main/java/package/web/rest/errors/ExceptionTranslator.java.ejs +++ b/generators/server/templates/src/main/java/package/web/rest/errors/ExceptionTranslator.java.ejs @@ -113,18 +113,18 @@ _%> @Override public <%- returnType %> process(@Nullable ResponseEntity entity, <%= requestClass %> request) { if (entity == null) { -<%_ if (!reactive) { _%> - return null; -<%_ } else { _%> +<%_ if (reactive) { _%> return Mono.empty(); +<%_ } else { _%> + return null; <%_ } _%> } Problem problem = entity.getBody(); if (!(problem instanceof ConstraintViolationProblem || problem instanceof DefaultProblem)) { -<%_ if (!reactive) { _%> - return entity; -<%_ } else { _%> +<%_ if (reactive) { _%> return Mono.just(entity); +<%_ } else { _%> + return entity; <%_ } _%> } @@ -136,10 +136,10 @@ _%> .withType(Problem.DEFAULT_TYPE.equals(problem.getType()) ? ErrorConstants.DEFAULT_TYPE : problem.getType()) .withStatus(problem.getStatus()) .withTitle(problem.getTitle()) -<%_ if (!reactive) { _%> - .with(PATH_KEY, requestUri); -<%_ } else { _%> +<%_ if (reactive) { _%> .with(PATH_KEY, request.getRequest().getPath().value()); +<%_ } else { _%> + .with(PATH_KEY, requestUri); <%_ } _%> if (problem instanceof ConstraintViolationProblem) { @@ -160,7 +160,7 @@ _%> } @Override - public <%- returnType %> handle<%_ if (!reactive) { _%>MethodArgumentNotValid(MethodArgumentNotValidException<% } else { %>BindingResult(WebExchangeBindException<% } %> ex, @Nonnull <%= requestClass %> request) { + public <%- returnType %> handle<%_ if (reactive) { _%>BindingResult(WebExchangeBindException<% } else { %>MethodArgumentNotValid(MethodArgumentNotValidException<% } %> ex, @Nonnull <%= requestClass %> request) { BindingResult result = ex.getBindingResult(); List fieldErrors = result.getFieldErrors().stream() .map(f -> new FieldErrorVM(f.getObjectName().replaceFirst("<%= dtoSuffix %>$", ""), f.getField(), StringUtils.isNotBlank(f.getDefaultMessage()) ? f.getDefaultMessage() : f.getCode())) @@ -168,8 +168,8 @@ _%> Problem problem = Problem.builder() .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE) - .withTitle("<%_ if (!reactive) { _%>Method argument not valid<% } else { %>Data binding and validation failure<% } %>") - .withStatus(<% if (!reactive) { %>defaultConstraintViolationStatus()<% } else { %>Status.BAD_REQUEST<% } %>) + .withTitle("<%_ if (reactive) { _%>Data binding and validation failure<% } else { %>Method argument not valid<% } %>") + .withStatus(<% if (reactive) { %>Status.BAD_REQUEST<% } else { %>defaultConstraintViolationStatus()<% } %>) .with(MESSAGE_KEY, ErrorConstants.ERR_VALIDATION) .with(FIELD_ERRORS_KEY, fieldErrors) .build(); diff --git a/generators/server/templates/src/main/resources/logback-spring.xml.ejs b/generators/server/templates/src/main/resources/logback-spring.xml.ejs index fe9e4864811..3f27bb380d4 100644 --- a/generators/server/templates/src/main/resources/logback-spring.xml.ejs +++ b/generators/server/templates/src/main/resources/logback-spring.xml.ejs @@ -154,10 +154,10 @@ -<%_ if (!reactive) { _%> - -<%_ } else { _%> +<%_ if (reactive) { _%> +<%_ } else { _%> + <%_ } _%> diff --git a/generators/server/templates/src/test/java/package/security/SecurityUtilsUnitTest.java.ejs b/generators/server/templates/src/test/java/package/security/SecurityUtilsUnitTest.java.ejs index c008075ddff..b999f155cfd 100644 --- a/generators/server/templates/src/test/java/package/security/SecurityUtilsUnitTest.java.ejs +++ b/generators/server/templates/src/test/java/package/security/SecurityUtilsUnitTest.java.ejs @@ -44,9 +44,9 @@ import java.util.*; <%_ } else { _%> import java.util.ArrayList; import java.util.Collection; -<%_ if (!reactive) { _%> + <%_ if (!reactive) { _%> import java.util.Optional; -<%_ } _%> + <%_ } _%> <%_ } _%> import static org.assertj.core.api.Assertions.assertThat; @@ -59,7 +59,113 @@ import static org.springframework.security.oauth2.core.oidc.endpoint.OidcParamet */ class SecurityUtilsUnitTest { -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + @Test + void testgetCurrentUserLogin() { + String login = SecurityUtils.getCurrentUserLogin() + .contextWrite( + ReactiveSecurityContextHolder.withAuthentication( + new UsernamePasswordAuthenticationToken("admin", "admin") + ) + ) + .block(); + assertThat(login).isEqualTo("admin"); + } + <%_ if (authenticationTypeJwt) { _%> + + @Test + void testgetCurrentUserJWT() { + String jwt = SecurityUtils.getCurrentUserJWT() + .contextWrite( + ReactiveSecurityContextHolder.withAuthentication( + new UsernamePasswordAuthenticationToken("admin", "token") + ) + ) + .block(); + assertThat(jwt).isEqualTo("token"); + } + <%_ } _%> + + @Test + void testIsAuthenticated() { + Boolean isAuthenticated = SecurityUtils.isAuthenticated() + .contextWrite( + ReactiveSecurityContextHolder.withAuthentication( + new UsernamePasswordAuthenticationToken("admin", "admin") + ) + ) + .block(); + assertThat(isAuthenticated).isTrue(); + } + + @Test + void testAnonymousIsNotAuthenticated() { + Collection authorities = new ArrayList<>(); + authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS)); + Boolean isAuthenticated = SecurityUtils.isAuthenticated() + .contextWrite( + ReactiveSecurityContextHolder.withAuthentication( + new UsernamePasswordAuthenticationToken("admin", "admin", authorities) + ) + ) + .block(); + assertThat(isAuthenticated).isFalse(); + } + + @Test + void testHasCurrentUserAnyOfAuthorities() { + Collection authorities = new ArrayList<>(); + authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER)); + Context context = ReactiveSecurityContextHolder.withAuthentication( + new UsernamePasswordAuthenticationToken("admin", "admin", authorities) + ); + Boolean hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserAnyOfAuthorities(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN) + .contextWrite(context) + .block(); + assertThat(hasCurrentUserThisAuthority).isTrue(); + + hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserAnyOfAuthorities(AuthoritiesConstants.ANONYMOUS, AuthoritiesConstants.ADMIN) + .contextWrite(context) + .block(); + assertThat(hasCurrentUserThisAuthority).isFalse(); + } + + @Test + void testHasCurrentUserNoneOfAuthorities() { + Collection authorities = new ArrayList<>(); + authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER)); + Context context = ReactiveSecurityContextHolder.withAuthentication( + new UsernamePasswordAuthenticationToken("admin", "admin", authorities) + ); + Boolean hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserNoneOfAuthorities(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN) + .contextWrite(context) + .block(); + assertThat(hasCurrentUserThisAuthority).isFalse(); + + hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserNoneOfAuthorities(AuthoritiesConstants.ANONYMOUS, AuthoritiesConstants.ADMIN) + .contextWrite(context) + .block(); + assertThat(hasCurrentUserThisAuthority).isTrue(); + } + + @Test + void testHasCurrentUserThisAuthority() { + Collection authorities = new ArrayList<>(); + authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER)); + Context context = ReactiveSecurityContextHolder.withAuthentication( + new UsernamePasswordAuthenticationToken("admin", "admin", authorities) + ); + Boolean hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.USER) + .contextWrite(context) + .block(); + assertThat(hasCurrentUserThisAuthority).isTrue(); + + hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.ADMIN) + .contextWrite(context) + .block(); + assertThat(hasCurrentUserThisAuthority).isFalse(); + } +<%_ } else { /% Not reactive %/_%> @BeforeEach @AfterEach void cleanup() { @@ -192,112 +298,5 @@ class SecurityUtilsUnitTest { assertThat(SecurityUtils.hasCurrentUserNoneOfAuthorities(AuthoritiesConstants.ANONYMOUS, AuthoritiesConstants.ADMIN)).isTrue(); } <%_ } _%> -<%_ if (reactive) { _%> - @Test - void testgetCurrentUserLogin() { - String login = SecurityUtils.getCurrentUserLogin() - .contextWrite( - ReactiveSecurityContextHolder.withAuthentication( - new UsernamePasswordAuthenticationToken("admin", "admin") - ) - ) - .block(); - assertThat(login).isEqualTo("admin"); - } - <%_ if (authenticationTypeJwt) { _%> - - @Test - void testgetCurrentUserJWT() { - String jwt = SecurityUtils.getCurrentUserJWT() - .contextWrite( - ReactiveSecurityContextHolder.withAuthentication( - new UsernamePasswordAuthenticationToken("admin", "token") - ) - ) - .block(); - assertThat(jwt).isEqualTo("token"); - } - <%_ } _%> - - @Test - void testIsAuthenticated() { - Boolean isAuthenticated = SecurityUtils.isAuthenticated() - .contextWrite( - ReactiveSecurityContextHolder.withAuthentication( - new UsernamePasswordAuthenticationToken("admin", "admin") - ) - ) - .block(); - assertThat(isAuthenticated).isTrue(); - } - - @Test - void testAnonymousIsNotAuthenticated() { - Collection authorities = new ArrayList<>(); - authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS)); - Boolean isAuthenticated = SecurityUtils.isAuthenticated() - .contextWrite( - ReactiveSecurityContextHolder.withAuthentication( - new UsernamePasswordAuthenticationToken("admin", "admin", authorities) - ) - ) - .block(); - assertThat(isAuthenticated).isFalse(); - } - - @Test - void testHasCurrentUserAnyOfAuthorities() { - Collection authorities = new ArrayList<>(); - authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER)); - Context context = ReactiveSecurityContextHolder.withAuthentication( - new UsernamePasswordAuthenticationToken("admin", "admin", authorities) - ); - Boolean hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserAnyOfAuthorities(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN) - .contextWrite(context) - .block(); - assertThat(hasCurrentUserThisAuthority).isTrue(); - - hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserAnyOfAuthorities(AuthoritiesConstants.ANONYMOUS, AuthoritiesConstants.ADMIN) - .contextWrite(context) - .block(); - assertThat(hasCurrentUserThisAuthority).isFalse(); - } - - @Test - void testHasCurrentUserNoneOfAuthorities() { - Collection authorities = new ArrayList<>(); - authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER)); - Context context = ReactiveSecurityContextHolder.withAuthentication( - new UsernamePasswordAuthenticationToken("admin", "admin", authorities) - ); - Boolean hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserNoneOfAuthorities(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN) - .contextWrite(context) - .block(); - assertThat(hasCurrentUserThisAuthority).isFalse(); - - hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserNoneOfAuthorities(AuthoritiesConstants.ANONYMOUS, AuthoritiesConstants.ADMIN) - .contextWrite(context) - .block(); - assertThat(hasCurrentUserThisAuthority).isTrue(); - } - - @Test - void testHasCurrentUserThisAuthority() { - Collection authorities = new ArrayList<>(); - authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER)); - Context context = ReactiveSecurityContextHolder.withAuthentication( - new UsernamePasswordAuthenticationToken("admin", "admin", authorities) - ); - Boolean hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.USER) - .contextWrite(context) - .block(); - assertThat(hasCurrentUserThisAuthority).isTrue(); - - hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.ADMIN) - .contextWrite(context) - .block(); - assertThat(hasCurrentUserThisAuthority).isFalse(); - } -<%_ } _%> } diff --git a/generators/server/templates/src/test/java/package/security/jwt/JWTFilterTest.java.ejs b/generators/server/templates/src/test/java/package/security/jwt/JWTFilterTest.java.ejs index c66e8ad28bf..20ebde6efd9 100644 --- a/generators/server/templates/src/test/java/package/security/jwt/JWTFilterTest.java.ejs +++ b/generators/server/templates/src/test/java/package/security/jwt/JWTFilterTest.java.ejs @@ -86,17 +86,7 @@ class JWTFilterTest { Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER)) ); String jwt = tokenProvider.createToken(authentication, false); -<%_ if (!reactive) { _%> - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt); - request.setRequestURI("/api/test"); - MockHttpServletResponse response = new MockHttpServletResponse(); - MockFilterChain filterChain = new MockFilterChain(); - jwtFilter.doFilter(request, response, filterChain); - assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); - assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("test-user"); - assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).hasToString(jwt); -<%_ } else { _%> +<%_ if (reactive) { _%> MockServerHttpRequest.BaseBuilder request = MockServerHttpRequest .get("/api/test") .header(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt); @@ -110,13 +100,7 @@ class JWTFilterTest { .doOnSuccess(auth -> assertThat(auth.getCredentials().toString()).hasToString(jwt)) .then() ).block(); -<%_ } _%> - } - - @Test - void testJWTFilterInvalidToken()<% if (!reactive) { %> throws Exception<% } %> { - String jwt = "wrong_jwt"; -<%_ if (!reactive) { _%> +<%_ } else { _%> MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt); request.setRequestURI("/api/test"); @@ -124,8 +108,15 @@ class JWTFilterTest { MockFilterChain filterChain = new MockFilterChain(); jwtFilter.doFilter(request, response, filterChain); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); - assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); -<%_ } else { _%> + assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("test-user"); + assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).hasToString(jwt); +<%_ } _%> + } + + @Test + void testJWTFilterInvalidToken()<% if (!reactive) { %> throws Exception<% } %> { + String jwt = "wrong_jwt"; +<%_ if (reactive) { _%> MockServerHttpRequest.BaseBuilder request = MockServerHttpRequest .get("/api/test") .header(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt); @@ -138,20 +129,21 @@ class JWTFilterTest { .doOnSuccess(auth -> assertThat(auth).isNull()) .then() ).block(); -<%_ } _%> - } - - @Test - void testJWTFilterMissingAuthorization()<% if (!reactive) { %> throws Exception<% } %> { -<%_ if (!reactive) { _%> +<%_ } else { _%> MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt); request.setRequestURI("/api/test"); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain filterChain = new MockFilterChain(); jwtFilter.doFilter(request, response, filterChain); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); -<%_ } else { _%> +<%_ } _%> + } + + @Test + void testJWTFilterMissingAuthorization()<% if (!reactive) { %> throws Exception<% } %> { +<%_ if (reactive) { _%> MockServerHttpRequest.BaseBuilder request = MockServerHttpRequest .get("/api/test"); MockServerWebExchange exchange = MockServerWebExchange.from(request); @@ -163,21 +155,20 @@ class JWTFilterTest { .doOnSuccess(auth -> assertThat(auth).isNull()) .then() ).block(); -<%_ } _%> - } - - @Test - void testJWTFilterMissingToken()<% if (!reactive) { %> throws Exception<% } %> { -<%_ if (!reactive) { _%> +<%_ } else { _%> MockHttpServletRequest request = new MockHttpServletRequest(); - request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer "); request.setRequestURI("/api/test"); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain filterChain = new MockFilterChain(); jwtFilter.doFilter(request, response, filterChain); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); -<%_ } else { _%> +<%_ } _%> + } + + @Test + void testJWTFilterMissingToken()<% if (!reactive) { %> throws Exception<% } %> { +<%_ if (reactive) { _%> MockServerHttpRequest.BaseBuilder request = MockServerHttpRequest .get("/api/test") .header(JWTFilter.AUTHORIZATION_HEADER, "Bearer "); @@ -190,6 +181,15 @@ class JWTFilterTest { .doOnSuccess(auth -> assertThat(auth).isNull()) .then() ).block(); +<%_ } else { _%> + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer "); + request.setRequestURI("/api/test"); + MockHttpServletResponse response = new MockHttpServletResponse(); + MockFilterChain filterChain = new MockFilterChain(); + jwtFilter.doFilter(request, response, filterChain); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); <%_ } _%> } @@ -201,16 +201,7 @@ class JWTFilterTest { Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER)) ); String jwt = tokenProvider.createToken(authentication, false); -<%_ if (!reactive) { _%> - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Basic " + jwt); - request.setRequestURI("/api/test"); - MockHttpServletResponse response = new MockHttpServletResponse(); - MockFilterChain filterChain = new MockFilterChain(); - jwtFilter.doFilter(request, response, filterChain); - assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); - assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); -<%_ } else { _%> +<%_ if (reactive) { _%> MockServerHttpRequest.BaseBuilder request = MockServerHttpRequest .get("/api/test") .header(JWTFilter.AUTHORIZATION_HEADER, "Basic " + jwt); @@ -223,6 +214,15 @@ class JWTFilterTest { .doOnSuccess(auth -> assertThat(auth).isNull()) .then() ).block(); +<%_ } else { _%> + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Basic " + jwt); + request.setRequestURI("/api/test"); + MockHttpServletResponse response = new MockHttpServletResponse(); + MockFilterChain filterChain = new MockFilterChain(); + jwtFilter.doFilter(request, response, filterChain); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); <%_ } _%> } diff --git a/generators/server/templates/src/test/java/package/web/rest/AccountResourceIT.java.ejs b/generators/server/templates/src/test/java/package/web/rest/AccountResourceIT.java.ejs index c415a9fc29c..ac5e9b17b3a 100644 --- a/generators/server/templates/src/test/java/package/web/rest/AccountResourceIT.java.ejs +++ b/generators/server/templates/src/test/java/package/web/rest/AccountResourceIT.java.ejs @@ -55,10 +55,10 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; <%_ } _%> import org.springframework.beans.factory.annotation.Autowired; -<%_ if (!reactive) { _%> -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -<%_ } else { _%> +<%_ if (reactive) { _%> import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; +<%_ } else { _%> +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; <%_ } _%> <%_ if (reactive) { _%> import org.springframework.http.HttpStatus; @@ -93,23 +93,23 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.hasItem; <%_ } _%> import static <%= packageName %>.web.rest.AccountResourceIT.TEST_USER_LOGIN; -<%_ if (!reactive) { _%> +<%_ if (reactive && testsNeedCsrf) { _%> +import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf; +<%_ } else { _%> <%_ if (testsNeedCsrf) { _%> import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; <%_ } _%> import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; -<%_ } else if (testsNeedCsrf) { _%> -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf; <%_ } _%> /** * Integration tests for the {@link AccountResource} REST controller. */ -<%_ if (!reactive) { _%> -@AutoConfigureMockMvc -<%_ } else { _%> +<%_ if (reactive) { _%> @AutoConfigureWebTestClient(timeout = IntegrationTest.DEFAULT_TIMEOUT) +<%_ } else { _%> +@AutoConfigureMockMvc <%_ } _%> @WithMockUser(value = TEST_USER_LOGIN) @IntegrationTest @@ -141,10 +141,10 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan private PasswordEncoder passwordEncoder; @Autowired -<%_ if (!reactive) { _%> - private MockMvc restAccountMockMvc; -<%_ } else { _%> +<%_ if (reactive) { _%> private WebTestClient accountWebTestClient; +<%_ } else { _%> + private MockMvc restAccountMockMvc; <%_ } _%> <%_ if (databaseTypeMongodb || databaseTypeNeo4j) { _%> @@ -163,25 +163,33 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan <%_ } _%> @Test @WithUnauthenticatedMockUser -<%_ if (!reactive) { _%> - void testNonAuthenticatedUser() throws Exception { - restAccountMockMvc.perform(get("/api/authenticate") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string("")); -<%_ } else { _%> +<%_ if (reactive) { _%> void testNonAuthenticatedUser() { accountWebTestClient.get().uri("/api/authenticate") .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() .expectBody().isEmpty(); +<%_ } else { _%> + void testNonAuthenticatedUser() throws Exception { + restAccountMockMvc.perform(get("/api/authenticate") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string("")); <%_ } _%> } @Test -<%_ if (!reactive) { _%> - void testAuthenticatedUser() <% if (!reactive) { %>throws Exception <% } %>{ +<%_ if (reactive) { _%> + void testAuthenticatedUser() { + accountWebTestClient + .get().uri("/api/authenticate") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isOk() + .expectBody(String.class).isEqualTo(TEST_USER_LOGIN); +<%_ } else { _%> + void testAuthenticatedUser() throws Exception { restAccountMockMvc.perform(get("/api/authenticate") .with(request -> { request.setRemoteUser(TEST_USER_LOGIN); @@ -190,25 +198,17 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(TEST_USER_LOGIN)); -<%_ } else { _%> - void testAuthenticatedUser() { - accountWebTestClient - .get().uri("/api/authenticate") - .accept(MediaType.APPLICATION_JSON) - .exchange() - .expectStatus().isOk() - .expectBody(String.class).isEqualTo(TEST_USER_LOGIN); <%_ } _%> } @Test void testGetExistingAccount()<% if (!reactive) { %> throws Exception<% } %> { - <%_ if (searchEngineElasticsearch && reactive) { _%> +<%_ if (searchEngineElasticsearch && reactive) { _%> // Configure the mock search repository when(mockUserSearchRepository.save(any())) .thenAnswer(invocation -> Mono.just(invocation.getArgument(0))); - <%_ } _%> +<%_ } _%> Set authorities = new HashSet<>(); authorities.add(AuthoritiesConstants.ADMIN); @@ -217,28 +217,14 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan user.setFirstName("john"); user.setLastName("doe"); user.setEmail("john.doe@jhipster.com"); - <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeNeo4j) { _%> +<%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeNeo4j) { _%> user.setImageUrl("http://placehold.it/50x50"); - <%_ } _%> +<%_ } _%> user.setLangKey("en"); user.setAuthorities(authorities); userService.createUser(user)<% if (reactive) { %>.block()<% } %>; - <%_ if (!reactive) { _%> - 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)) - .andExpect(jsonPath("$.firstName").value("john")) - .andExpect(jsonPath("$.lastName").value("doe")) - .andExpect(jsonPath("$.email").value("john.doe@jhipster.com")) - <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeNeo4j) { _%> - .andExpect(jsonPath("$.imageUrl").value("http://placehold.it/50x50")) - <%_ } _%> - .andExpect(jsonPath("$.langKey").value("en")) - .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN)); - <%_ } else { _%> +<%_ if (reactive) { _%> accountWebTestClient.get().uri("/api/account") .accept(MediaType.APPLICATION_JSON) .exchange() @@ -249,26 +235,41 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan .jsonPath("$.firstName").isEqualTo("john") .jsonPath("$.lastName").isEqualTo("doe") .jsonPath("$.email").isEqualTo("john.doe@jhipster.com") - <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeNeo4j) { _%> + <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeNeo4j) { _%> .jsonPath("$.imageUrl").isEqualTo("http://placehold.it/50x50") - <%_ } _%> + <%_ } _%> .jsonPath("$.langKey").isEqualTo("en") .jsonPath("$.authorities").isEqualTo(AuthoritiesConstants.ADMIN); +<%_ } else { _%> + 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)) + .andExpect(jsonPath("$.firstName").value("john")) + .andExpect(jsonPath("$.lastName").value("doe")) + .andExpect(jsonPath("$.email").value("john.doe@jhipster.com")) + <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeNeo4j) { _%> + .andExpect(jsonPath("$.imageUrl").value("http://placehold.it/50x50")) <%_ } _%> + .andExpect(jsonPath("$.langKey").value("en")) + .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN)); + +<%_ } _%> } @Test -<%_ if (!reactive) { _%> - void testGetUnknownAccount() throws Exception { - restAccountMockMvc.perform(get("/api/account") - .accept(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(status().isInternalServerError()); -<%_ } else { _%> +<%_ if (reactive) { _%> void testGetUnknownAccount() { accountWebTestClient.get().uri("/api/account") .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); +<%_ } else { _%> + void testGetUnknownAccount() throws Exception { + restAccountMockMvc.perform(get("/api/account") + .accept(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(status().isInternalServerError()); <%_ } _%> } @@ -296,19 +297,19 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); assertThat(userRepository.findOneByLogin("test-register-valid")<% if (reactive) { %>.blockOptional()<% } %>).isEmpty(); -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + accountWebTestClient.post().uri("/api/register") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(TestUtil.convertObjectToJsonBytes(validUser)) + .exchange() + .expectStatus().isCreated(); +<%_ } else { _%> restAccountMockMvc.perform( post("/api/register") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(validUser))<% if (testsNeedCsrf) { %> .with(csrf())<% } %>) .andExpect(status().isCreated()); -<%_ } else { _%> - accountWebTestClient.post().uri("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(TestUtil.convertObjectToJsonBytes(validUser)) - .exchange() - .expectStatus().isCreated(); <%_ } _%> assertThat(userRepository.findOneByLogin("test-register-valid")<% if (reactive) { %>.blockOptional()<% } %>).isPresent(); @@ -369,19 +370,19 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + accountWebTestClient.post().uri("/api/register") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(TestUtil.convertObjectToJsonBytes(invalidUser)) + .exchange() + .expectStatus().isBadRequest(); +<%_ } else { _%> restAccountMockMvc.perform( post("/api/register") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(invalidUser))<% if (testsNeedCsrf) { %> .with(csrf())<% } %>) .andExpect(status().isBadRequest()); -<%_ } else { _%> - accountWebTestClient.post().uri("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(TestUtil.convertObjectToJsonBytes(invalidUser)) - .exchange() - .expectStatus().isBadRequest(); <%_ } _%> Optional<<%= asEntity('User') %>> user = userRepository.findOneByLogin("bob")<% if (reactive) { %>.blockOptional()<% } %>; @@ -406,19 +407,19 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + accountWebTestClient.post().uri("/api/register") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(TestUtil.convertObjectToJsonBytes(invalidUser)) + .exchange() + .expectStatus().isBadRequest(); +<%_ } else { _%> restAccountMockMvc.perform( post("/api/register") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(invalidUser))<% if (testsNeedCsrf) { %> .with(csrf())<% } %>) .andExpect(status().isBadRequest()); -<%_ } else { _%> - accountWebTestClient.post().uri("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(TestUtil.convertObjectToJsonBytes(invalidUser)) - .exchange() - .expectStatus().isBadRequest(); <%_ } _%> Optional<<%= asEntity('User') %>> user = userRepository.findOneByLogin("bob")<% if (reactive) { %>.blockOptional()<% } %>; @@ -443,19 +444,19 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + accountWebTestClient.post().uri("/api/register") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(TestUtil.convertObjectToJsonBytes(invalidUser)) + .exchange() + .expectStatus().isBadRequest(); +<%_ } else { _%> restAccountMockMvc.perform( post("/api/register") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(invalidUser))<% if (testsNeedCsrf) { %> .with(csrf())<% } %>) .andExpect(status().isBadRequest()); -<%_ } else { _%> - accountWebTestClient.post().uri("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(TestUtil.convertObjectToJsonBytes(invalidUser)) - .exchange() - .expectStatus().isBadRequest(); <%_ } _%> Optional<<%= asEntity('User') %>> user = userRepository.findOneByLogin("bob")<% if (reactive) { %>.blockOptional()<% } %>; @@ -506,35 +507,35 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities())); // First user -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + accountWebTestClient.post().uri("/api/register") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(TestUtil.convertObjectToJsonBytes(firstUser)) + .exchange() + .expectStatus().isCreated(); +<%_ } else { _%> restAccountMockMvc.perform( post("/api/register") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(firstUser))<% if (testsNeedCsrf) { %> .with(csrf())<% } %>) .andExpect(status().isCreated()); -<%_ } else { _%> +<%_ } _%> + + // Second (non activated) user +<%_ if (reactive) { _%> accountWebTestClient.post().uri("/api/register") .contentType(MediaType.APPLICATION_JSON) - .bodyValue(TestUtil.convertObjectToJsonBytes(firstUser)) + .bodyValue(TestUtil.convertObjectToJsonBytes(secondUser)) .exchange() .expectStatus().isCreated(); -<%_ } _%> - - // Second (non activated) user -<%_ if (!reactive) { _%> +<%_ } else { _%> restAccountMockMvc.perform( post("/api/register") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(secondUser))<% if (testsNeedCsrf) { %> .with(csrf())<% } %>) .andExpect(status().isCreated()); -<%_ } else { _%> - accountWebTestClient.post().uri("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(TestUtil.convertObjectToJsonBytes(secondUser)) - .exchange() - .expectStatus().isCreated(); <%_ } _%> Optional<<%= asEntity('User') %>> testUser = userRepository.findOneByEmailIgnoreCase("alice2@example.com")<% if (reactive) { %>.blockOptional()<% } %>; @@ -543,19 +544,19 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan userRepository.save(testUser.get())<% if (reactive) { %>.block()<% } %>; // Second (already activated) user -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + accountWebTestClient.post().uri("/api/register") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(TestUtil.convertObjectToJsonBytes(secondUser)) + .exchange() + .expectStatus().isBadRequest(); +<%_ } else { _%> restAccountMockMvc.perform( post("/api/register") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(secondUser))<% if (testsNeedCsrf) { %> .with(csrf())<% } %>) .andExpect(status().is4xxClientError()); -<%_ } else { _%> - accountWebTestClient.post().uri("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(TestUtil.convertObjectToJsonBytes(secondUser)) - .exchange() - .expectStatus().isBadRequest(); <%_ } _%> } @@ -584,19 +585,19 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); // Register first user -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + accountWebTestClient.post().uri("/api/register") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(TestUtil.convertObjectToJsonBytes(firstUser)) + .exchange() + .expectStatus().isCreated(); +<%_ } else { _%> restAccountMockMvc.perform( post("/api/register") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(firstUser))<% if (testsNeedCsrf) { %> .with(csrf())<% } %>) .andExpect(status().isCreated()); -<%_ } else { _%> - accountWebTestClient.post().uri("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(TestUtil.convertObjectToJsonBytes(firstUser)) - .exchange() - .expectStatus().isCreated(); <%_ } _%> Optional<<%= asEntity('User') %>> testUser1 = userRepository.findOneByLogin("test-register-duplicate-email")<% if (reactive) { %>.blockOptional()<% } %>; @@ -616,19 +617,19 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities())); // Register second (non activated) user -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + accountWebTestClient.post().uri("/api/register") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(TestUtil.convertObjectToJsonBytes(secondUser)) + .exchange() + .expectStatus().isCreated(); +<%_ } else { _%> restAccountMockMvc.perform( post("/api/register") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(secondUser))<% if (testsNeedCsrf) { %> .with(csrf())<% } %>) .andExpect(status().isCreated()); -<%_ } else { _%> - accountWebTestClient.post().uri("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(TestUtil.convertObjectToJsonBytes(secondUser)) - .exchange() - .expectStatus().isCreated(); <%_ } _%> Optional<<%= asEntity('User') %>> testUser2 = userRepository.findOneByLogin("test-register-duplicate-email")<% if (reactive) { %>.blockOptional()<% } %>; @@ -652,19 +653,19 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan userWithUpperCaseEmail.setAuthorities(new HashSet<>(firstUser.getAuthorities())); // Register third (not activated) user -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + accountWebTestClient.post().uri("/api/register") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(TestUtil.convertObjectToJsonBytes(userWithUpperCaseEmail)) + .exchange() + .expectStatus().isCreated(); +<%_ } else { _%> restAccountMockMvc.perform( post("/api/register") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(userWithUpperCaseEmail))<% if (testsNeedCsrf) { %> .with(csrf())<% } %>) .andExpect(status().isCreated()); -<%_ } else { _%> - accountWebTestClient.post().uri("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(TestUtil.convertObjectToJsonBytes(userWithUpperCaseEmail)) - .exchange() - .expectStatus().isCreated(); <%_ } _%> Optional<<%= asEntity('User') %>> testUser4 = userRepository.findOneByLogin("test-register-duplicate-email-3")<% if (reactive) { %>.blockOptional()<% } %>; @@ -675,19 +676,19 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan userService.updateUser((new <%= asDto('AdminUser') %>(testUser4.get())))<% if (reactive) { %>.block()<% } %>; // Register 4th (already activated) user -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + accountWebTestClient.post().uri("/api/register") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(TestUtil.convertObjectToJsonBytes(secondUser)) + .exchange() + .expectStatus().is4xxClientError(); +<%_ } else { _%> restAccountMockMvc.perform( post("/api/register") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(secondUser))<% if (testsNeedCsrf) { %> .with(csrf())<% } %>) .andExpect(status().is4xxClientError()); -<%_ } else { _%> - accountWebTestClient.post().uri("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(TestUtil.convertObjectToJsonBytes(secondUser)) - .exchange() - .expectStatus().is4xxClientError(); <%_ } _%> } @@ -715,19 +716,19 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan .thenAnswer(invocation -> Mono.just(invocation.getArgument(0))); <%_ } _%> -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + accountWebTestClient.post().uri("/api/register") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(TestUtil.convertObjectToJsonBytes(validUser)) + .exchange() + .expectStatus().isCreated(); +<%_ } else { _%> restAccountMockMvc.perform( post("/api/register") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(validUser))<% if (testsNeedCsrf) { %> .with(csrf())<% } %>) .andExpect(status().isCreated()); -<%_ } else { _%> - accountWebTestClient.post().uri("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(TestUtil.convertObjectToJsonBytes(validUser)) - .exchange() - .expectStatus().isCreated(); <%_ } _%> Optional<<%= asEntity('User') %>> userDup = userRepository.findOne<% if (databaseTypeSql) { %>WithAuthorities<% } %>ByLogin("badguy")<% if (reactive) { %>.blockOptional()<% } %>; @@ -763,16 +764,16 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan userRepository.save<% if (databaseTypeSql && !reactive) { %>AndFlush<% } %>(user)<% if (reactive) { %>.block()<% } %>; -<%_ if (!reactive) { _%> - restAccountMockMvc.perform(get("/api/activate?key={activationKey}", activationKey)) - .andExpect(status().isOk()); -<%_ } else { _%> +<%_ if (reactive) { _%> accountWebTestClient.get().uri("/api/activate?key={activationKey}", activationKey) .exchange() .expectStatus().isOk(); +<%_ } else { _%> + restAccountMockMvc.perform(get("/api/activate?key={activationKey}", activationKey)) + .andExpect(status().isOk()); <%_ } _%> - user = userRepository.findOneByLogin(user.getLogin())<%_ if (!reactive) { _%>.orElse(null)<% } else { %>.block()<% } %>; + user = userRepository.findOneByLogin(user.getLogin())<%_ if (reactive) { _%>.block()<% } else { %>.orElse(null)<% } %>; assertThat(user.isActivated()).isTrue(); } @@ -781,13 +782,13 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan @Transactional <%_ } _%> void testActivateAccountWithWrongKey() <% if (!reactive) { %>throws Exception <% } %>{ -<%_ if (!reactive) { _%> - restAccountMockMvc.perform(get("/api/activate?key=wrongActivationKey")) - .andExpect(status().isInternalServerError()); -<%_ } else { _%> +<%_ if (reactive) { _%> accountWebTestClient.get().uri("/api/activate?key=wrongActivationKey") .exchange() .expectStatus().isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); +<%_ } else { _%> + restAccountMockMvc.perform(get("/api/activate?key=wrongActivationKey")) + .andExpect(status().isInternalServerError()); <%_ } _%> } @@ -828,22 +829,22 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + accountWebTestClient.post().uri("/api/account") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(TestUtil.convertObjectToJsonBytes(userDTO)) + .exchange() + .expectStatus().isOk(); +<%_ } else { _%> restAccountMockMvc.perform( post("/api/account") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(userDTO))<% if (testsNeedCsrf) { %> .with(csrf())<% } %>) .andExpect(status().isOk()); -<%_ } else { _%> - accountWebTestClient.post().uri("/api/account") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(TestUtil.convertObjectToJsonBytes(userDTO)) - .exchange() - .expectStatus().isOk(); <%_ } _%> - <%= asEntity('User') %> updatedUser = userRepository.findOne<% if (databaseTypeSql) { %>WithAuthorities<% } %>ByLogin(user.getLogin())<%_ if (!reactive) { _%>.orElse(null)<% } else { %>.block()<% } %>; + <%= asEntity('User') %> updatedUser = userRepository.findOne<% if (databaseTypeSql) { %>WithAuthorities<% } %>ByLogin(user.getLogin())<%_ if (reactive) { _%>.block()<% } else { %>.orElse(null)<% } %>; assertThat(updatedUser.getFirstName()).isEqualTo(userDTO.getFirstName()); assertThat(updatedUser.getLastName()).isEqualTo(userDTO.getLastName()); assertThat(updatedUser.getEmail()).isEqualTo(userDTO.getEmail()); @@ -888,19 +889,19 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + accountWebTestClient.post().uri("/api/account") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(TestUtil.convertObjectToJsonBytes(userDTO)) + .exchange() + .expectStatus().isBadRequest(); +<%_ } else { _%> restAccountMockMvc.perform( post("/api/account") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(userDTO))<% if (testsNeedCsrf) { %> .with(csrf())<% } %>) .andExpect(status().isBadRequest()); -<%_ } else { _%> - accountWebTestClient.post().uri("/api/account") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(TestUtil.convertObjectToJsonBytes(userDTO)) - .exchange() - .expectStatus().isBadRequest(); <%_ } _%> assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")<% if (reactive) { %>.blockOptional()<% } %>).isNotPresent(); @@ -951,22 +952,22 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + accountWebTestClient.post().uri("/api/account") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(TestUtil.convertObjectToJsonBytes(userDTO)) + .exchange() + .expectStatus().isBadRequest(); +<%_ } else { _%> restAccountMockMvc.perform( post("/api/account") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(userDTO))<% if (testsNeedCsrf) { %> .with(csrf())<% } %>) .andExpect(status().isBadRequest()); -<%_ } else { _%> - accountWebTestClient.post().uri("/api/account") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(TestUtil.convertObjectToJsonBytes(userDTO)) - .exchange() - .expectStatus().isBadRequest(); <%_ } _%> - <%= asEntity('User') %> updatedUser = userRepository.findOneByLogin("save-existing-email")<%_ if (!reactive) { _%>.orElse(null)<% } else { %>.block()<% } %>; + <%= asEntity('User') %> updatedUser = userRepository.findOneByLogin("save-existing-email")<%_ if (reactive) { _%>.block()<% } else { %>.orElse(null)<% } %>; assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email@example.com"); } @@ -1007,22 +1008,22 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + accountWebTestClient.post().uri("/api/account") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(TestUtil.convertObjectToJsonBytes(userDTO)) + .exchange() + .expectStatus().isOk(); +<%_ } else { _%> restAccountMockMvc.perform( post("/api/account") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(userDTO))<% if (testsNeedCsrf) { %> .with(csrf())<% } %>) .andExpect(status().isOk()); -<%_ } else { _%> - accountWebTestClient.post().uri("/api/account") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(TestUtil.convertObjectToJsonBytes(userDTO)) - .exchange() - .expectStatus().isOk(); <%_ } _%> - <%= asEntity('User') %> updatedUser = userRepository.findOneByLogin("save-existing-email-and-login")<%_ if (!reactive) { _%>.orElse(null)<% } else { %>.block()<% } %>; + <%= asEntity('User') %> updatedUser = userRepository.findOneByLogin("save-existing-email-and-login")<%_ if (reactive) { _%>.block()<% } else { %>.orElse(null)<% } %>; assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email-and-login@example.com"); } @@ -1045,19 +1046,19 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan <%_ } _%> userRepository.save<% if (databaseTypeSql && !reactive) { %>AndFlush<% } %>(user)<% if (reactive) { %>.block()<% } %>; -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + accountWebTestClient.post().uri("/api/account/change-password") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO("1"+currentPassword, "new password"))) + .exchange() + .expectStatus().isBadRequest(); +<%_ } else { _%> restAccountMockMvc.perform(post("/api/account/change-password") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO("1"+currentPassword, "new password"))) <%_ if (testsNeedCsrf) { _%> .with(csrf())<%_ } _%>) .andExpect(status().isBadRequest()); -<%_ } else { _%> - accountWebTestClient.post().uri("/api/account/change-password") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO("1"+currentPassword, "new password"))) - .exchange() - .expectStatus().isBadRequest(); <%_ } _%> <%= asEntity('User') %> updatedUser = userRepository.findOneByLogin("change-password-wrong-existing-password")<%_ if (!reactive) { _%>.orElse(null)<% } else { %>.block()<% } %>; @@ -1084,22 +1085,22 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan <%_ } _%> userRepository.save<% if (databaseTypeSql && !reactive) { %>AndFlush<% } %>(user)<% if (reactive) { %>.block()<% } %>; -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + accountWebTestClient.post().uri("/api/account/change-password") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "new password"))) + .exchange() + .expectStatus().isOk(); +<%_ } else { _%> restAccountMockMvc.perform(post("/api/account/change-password") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "new password"))) <%_ if (testsNeedCsrf) { _%> .with(csrf())<%_ } _%>) .andExpect(status().isOk()); -<%_ } else { _%> - accountWebTestClient.post().uri("/api/account/change-password") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "new password"))) - .exchange() - .expectStatus().isOk(); <%_ } _%> - <%= asEntity('User') %> updatedUser = userRepository.findOneByLogin("change-password")<%_ if (!reactive) { _%>.orElse(null)<% } else { %>.block()<% } %>; + <%= asEntity('User') %> updatedUser = userRepository.findOneByLogin("change-password")<%_ if (reactive) { _%>.block()<% } else { %>.orElse(null)<% } %>; assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isTrue(); } @@ -1124,22 +1125,22 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MIN_LENGTH - 1); -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + accountWebTestClient.post().uri("/api/account/change-password") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword))) + .exchange() + .expectStatus().isBadRequest(); +<%_ } else { _%> restAccountMockMvc.perform(post("/api/account/change-password") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword))) <%_ if (testsNeedCsrf) { _%> .with(csrf())<%_ } _%>) .andExpect(status().isBadRequest()); -<%_ } else { _%> - accountWebTestClient.post().uri("/api/account/change-password") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword))) - .exchange() - .expectStatus().isBadRequest(); <%_ } _%> - <%= asEntity('User') %> updatedUser = userRepository.findOneByLogin("change-password-too-small")<%_ if (!reactive) { _%>.orElse(null)<% } else { %>.block()<% } %>; + <%= asEntity('User') %> updatedUser = userRepository.findOneByLogin("change-password-too-small")<%_ if (reactive) { _%>.block()<% } else { %>.orElse(null)<% } %>; assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); } @@ -1164,19 +1165,19 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MAX_LENGTH + 1); -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + accountWebTestClient.post().uri("/api/account/change-password") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword))) + .exchange() + .expectStatus().isBadRequest(); +<%_ } else { _%> restAccountMockMvc.perform(post("/api/account/change-password") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword))) <%_ if (testsNeedCsrf) { _%> .with(csrf())<%_ } _%>) .andExpect(status().isBadRequest()); -<%_ } else { _%> - accountWebTestClient.post().uri("/api/account/change-password") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword))) - .exchange() - .expectStatus().isBadRequest(); <%_ } _%> <%= asEntity('User') %> updatedUser = userRepository.findOneByLogin("change-password-too-long")<%_ if (!reactive) { _%>.orElse(null)<% } else { %>.block()<% } %>; @@ -1202,22 +1203,22 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan <%_ } _%> userRepository.save<% if (databaseTypeSql && !reactive) { %>AndFlush<% } %>(user)<% if (reactive) { %>.block()<% } %>; -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + accountWebTestClient.post().uri("/api/account/change-password") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, ""))) + .exchange() + .expectStatus().isBadRequest(); +<%_ } else { _%> restAccountMockMvc.perform(post("/api/account/change-password") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, ""))) <%_ if (testsNeedCsrf) { _%> .with(csrf())<%_ } _%>) .andExpect(status().isBadRequest()); -<%_ } else { _%> - accountWebTestClient.post().uri("/api/account/change-password") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, ""))) - .exchange() - .expectStatus().isBadRequest(); <%_ } _%> - <%= asEntity('User') %> updatedUser = userRepository.findOneByLogin("change-password-empty")<%_ if (!reactive) { _%>.orElse(null)<% } else { %>.block()<% } %>; + <%= asEntity('User') %> updatedUser = userRepository.findOneByLogin("change-password-empty")<%_ if (reactive) { _%>.block()<% } else { %>.orElse(null)<% } %>; assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); } <%_ if (authenticationTypeSession && !reactive) { _%> @@ -1331,17 +1332,17 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan <%_ } _%> userRepository.save<% if (databaseTypeSql && !reactive) { %>AndFlush<% } %>(user)<% if (reactive) { %>.block()<% } %>; -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + accountWebTestClient.post().uri("/api/account/reset-password/init") + .bodyValue("password-reset@example.com") + .exchange() + .expectStatus().isOk(); +<%_ } else { _%> restAccountMockMvc.perform(post("/api/account/reset-password/init") .content("password-reset@example.com") <%_ if (testsNeedCsrf) { _%> .with(csrf())<%_ } _%>) .andExpect(status().isOk()); -<%_ } else { _%> - accountWebTestClient.post().uri("/api/account/reset-password/init") - .bodyValue("password-reset@example.com") - .exchange() - .expectStatus().isOk(); <%_ } _%> } @@ -1363,34 +1364,34 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan <%_ } _%> userRepository.save<% if (databaseTypeSql && !reactive) { %>AndFlush<% } %>(user)<% if (reactive) { %>.block()<% } %>; -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + accountWebTestClient.post().uri("/api/account/reset-password/init") + .bodyValue("password-reset-upper-case@EXAMPLE.COM") + .exchange() + .expectStatus().isOk(); +<%_ } else { _%> restAccountMockMvc.perform(post("/api/account/reset-password/init") .content("password-reset-upper-case@EXAMPLE.COM") <%_ if (testsNeedCsrf) { _%> .with(csrf())<%_ } _%>) .andExpect(status().isOk()); -<%_ } else { _%> - accountWebTestClient.post().uri("/api/account/reset-password/init") - .bodyValue("password-reset-upper-case@EXAMPLE.COM") - .exchange() - .expectStatus().isOk(); <%_ } _%> } @Test -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + void testRequestPasswordResetWrongEmail() { + accountWebTestClient.post().uri("/api/account/reset-password/init") + .bodyValue("password-reset-wrong-email@example.com") + .exchange() + .expectStatus().isOk(); +<%_ } else { _%> void testRequestPasswordResetWrongEmail() <% if (!reactive) { %>throws Exception <% } %>{ restAccountMockMvc.perform( post("/api/account/reset-password/init") .content("password-reset-wrong-email@example.com")<% if (testsNeedCsrf) { %> .with(csrf())<% } %>) .andExpect(status().isOk()); -<%_ } else { _%> - void testRequestPasswordResetWrongEmail() { - accountWebTestClient.post().uri("/api/account/reset-password/init") - .bodyValue("password-reset-wrong-email@example.com") - .exchange() - .expectStatus().isOk(); <%_ } _%> } @@ -1417,22 +1418,22 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan keyAndPassword.setKey(user.getResetKey()); keyAndPassword.setNewPassword("new password"); -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + accountWebTestClient.post().uri("/api/account/reset-password/finish") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(TestUtil.convertObjectToJsonBytes(keyAndPassword)) + .exchange() + .expectStatus().isOk(); +<%_ } else { _%> restAccountMockMvc.perform( post("/api/account/reset-password/finish") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))<% if (testsNeedCsrf) { %> .with(csrf())<% } %>) .andExpect(status().isOk()); -<%_ } else { _%> - accountWebTestClient.post().uri("/api/account/reset-password/finish") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(TestUtil.convertObjectToJsonBytes(keyAndPassword)) - .exchange() - .expectStatus().isOk(); <%_ } _%> - <%= asEntity('User') %> updatedUser = userRepository.findOneByLogin(user.getLogin())<%_ if (!reactive) { _%>.orElse(null)<% } else { %>.block()<% } %>; + <%= asEntity('User') %> updatedUser = userRepository.findOneByLogin(user.getLogin())<%_ if (reactive) { _%>.block()<% } else { %>.orElse(null)<% } %>; assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isTrue(); } @@ -1459,19 +1460,19 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan keyAndPassword.setKey(user.getResetKey()); keyAndPassword.setNewPassword("foo"); -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + accountWebTestClient.post().uri("/api/account/reset-password/finish") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(TestUtil.convertObjectToJsonBytes(keyAndPassword)) + .exchange() + .expectStatus().isBadRequest(); +<%_ } else { _%> restAccountMockMvc.perform( post("/api/account/reset-password/finish") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))<% if (testsNeedCsrf) { %> .with(csrf())<% } %>) .andExpect(status().isBadRequest()); -<%_ } else { _%> - accountWebTestClient.post().uri("/api/account/reset-password/finish") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(TestUtil.convertObjectToJsonBytes(keyAndPassword)) - .exchange() - .expectStatus().isBadRequest(); <%_ } _%> <%= asEntity('User') %> updatedUser = userRepository.findOneByLogin(user.getLogin())<%_ if (!reactive) { _%>.orElse(null)<% } else { %>.block()<% } %>; @@ -1487,19 +1488,19 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan keyAndPassword.setKey("wrong reset key"); keyAndPassword.setNewPassword("new password"); -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + accountWebTestClient.post().uri("/api/account/reset-password/finish") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(TestUtil.convertObjectToJsonBytes(keyAndPassword)) + .exchange() + .expectStatus().isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); +<%_ } else { _%> restAccountMockMvc.perform( post("/api/account/reset-password/finish") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))<% if (testsNeedCsrf) { %> .with(csrf())<% } %>) .andExpect(status().isInternalServerError()); -<%_ } else { _%> - accountWebTestClient.post().uri("/api/account/reset-password/finish") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(TestUtil.convertObjectToJsonBytes(keyAndPassword)) - .exchange() - .expectStatus().isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); <%_ } _%> } } diff --git a/generators/server/templates/src/test/java/package/web/rest/AccountResourceIT_oauth2.java.ejs b/generators/server/templates/src/test/java/package/web/rest/AccountResourceIT_oauth2.java.ejs index 626cd6976a7..0b8f678e422 100644 --- a/generators/server/templates/src/test/java/package/web/rest/AccountResourceIT_oauth2.java.ejs +++ b/generators/server/templates/src/test/java/package/web/rest/AccountResourceIT_oauth2.java.ejs @@ -20,13 +20,13 @@ package <%= packageName %>.web.rest; import static <%= packageName %>.test.util.OAuth2TestUtil.TEST_USER_LOGIN; import static <%= packageName %>.test.util.OAuth2TestUtil.registerAuthenticationToken; -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> +import static <%= packageName %>.test.util.OAuth2TestUtil.authenticationToken; +import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.*; +<%_ } else { _%> import static <%= packageName %>.test.util.OAuth2TestUtil.testAuthenticationToken; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; -<%_ } else { _%> -import static <%= packageName %>.test.util.OAuth2TestUtil.authenticationToken; -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.*; <%_ if (searchEngineElasticsearch) { _%> import static org.mockito.Mockito.*; <%_ } _%> @@ -42,17 +42,7 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; -<%_ if (!reactive) { _%> -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService; -import org.springframework.security.oauth2.client.registration.ClientRegistration; -import org.springframework.security.test.context.TestSecurityContextHolder; -import org.springframework.test.web.servlet.MockMvc; - <%_ if (databaseTypeSql && !reactive) { _%> -import org.springframework.transaction.annotation.Transactional; - <%_ } _%> - -<%_ } else { _%> +<%_ if (reactive) { _%> import org.junit.jupiter.api.BeforeEach; import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientService; @@ -65,30 +55,31 @@ import reactor.core.publisher.Mono; import java.util.Collections; import java.util.HashMap; import java.util.Map; +<%_ } else { _%> +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService; +import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.test.context.TestSecurityContextHolder; +import org.springframework.test.web.servlet.MockMvc; + <%_ if (databaseTypeSql && !reactive) { _%> +import org.springframework.transaction.annotation.Transactional; + <%_ } _%> + <%_ } _%> /** * Integration tests for the {@link AccountResource} REST controller. */ -<%_ if (!reactive) { _%> -@AutoConfigureMockMvc -<%_ } else { _%> +<%_ if (reactive) { _%> @AutoConfigureWebTestClient(timeout = IntegrationTest.DEFAULT_TIMEOUT) +<%_ } else { _%> +@AutoConfigureMockMvc <%_ } _%> @WithMockUser(value = TEST_USER_LOGIN) @IntegrationTest class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassandraTest <% } %>{ -<%_ if (!reactive) { _%> - @Autowired - private MockMvc restAccountMockMvc; - - @Autowired - OAuth2AuthorizedClientService authorizedClientService; - - @Autowired - ClientRegistration clientRegistration; -<%_ } else { _%> +<%_ if (reactive) { _%> private Map claims; @Autowired @@ -99,6 +90,15 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan @Autowired private ClientRegistration clientRegistration; +<%_ } else { _%> + @Autowired + private MockMvc restAccountMockMvc; + + @Autowired + OAuth2AuthorizedClientService authorizedClientService; + + @Autowired + ClientRegistration clientRegistration; <%_ } _%> <%_ if (reactive) { _%> @@ -116,19 +116,7 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan @Transactional <%_ } _%> void testGetExistingAccount() <% if (!reactive) { %>throws Exception <% } %>{ -<%_ if (!reactive) { _%> - TestSecurityContextHolder - .getContext() - .setAuthentication(registerAuthenticationToken(authorizedClientService, clientRegistration, testAuthenticationToken())); - - 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)) - .andExpect(jsonPath("$.email").value("john.doe@jhipster.com")) - .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN)); -<%_ } else { _%> +<%_ if (reactive) { _%> webTestClient .mutateWith(mockAuthentication(registerAuthenticationToken(authorizedClientService, clientRegistration, authenticationToken(claims)))) .mutateWith(csrf()) @@ -141,44 +129,62 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan .jsonPath("$.login").isEqualTo("jane") .jsonPath("$.email").isEqualTo("jane.doe@jhipster.com") .jsonPath("$.authorities").isEqualTo(AuthoritiesConstants.ADMIN); +<%_ } else { _%> + TestSecurityContextHolder + .getContext() + .setAuthentication(registerAuthenticationToken(authorizedClientService, clientRegistration, testAuthenticationToken())); + + 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)) + .andExpect(jsonPath("$.email").value("john.doe@jhipster.com")) + .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN)); <%_ } _%> } @Test void testGetUnknownAccount() <% if (!reactive) { %>throws Exception <% } %>{ -<%_ if (!reactive) { _%> - restAccountMockMvc.perform(get("/api/account") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isInternalServerError()); -<%_ } else { _%> +<%_ if (reactive) { _%> webTestClient.get().uri("/api/account") .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().is5xxServerError(); +<%_ } else { _%> + restAccountMockMvc.perform(get("/api/account") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isInternalServerError()); <%_ } _%> } @Test @WithUnauthenticatedMockUser -<%_ if (!reactive) { _%> void testNonAuthenticatedUser() <% if (!reactive) { %>throws Exception <% } %>{ - restAccountMockMvc.perform(get("/api/authenticate") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string("")); -<%_ } else { _%> - void testNonAuthenticatedUser() { +<%_ if (reactive) { _%> webTestClient.get().uri("/api/authenticate") .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() .expectBody().isEmpty(); +<%_ } else { _%> + restAccountMockMvc.perform(get("/api/authenticate") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string("")); <%_ } _%> } @Test -<%_ if (!reactive) { _%> void testAuthenticatedUser() <% if (!reactive) { %>throws Exception <% } %>{ +<%_ if (reactive) { _%> + webTestClient + .get().uri("/api/authenticate") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isOk() + .expectBody(String.class).isEqualTo(TEST_USER_LOGIN); +<%_ } else { _%> restAccountMockMvc.perform(get("/api/authenticate") .with(request -> { request.setRemoteUser(TEST_USER_LOGIN); @@ -187,14 +193,6 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(TEST_USER_LOGIN)); -<%_ } else { _%> - void testAuthenticatedUser() { - webTestClient - .get().uri("/api/authenticate") - .accept(MediaType.APPLICATION_JSON) - .exchange() - .expectStatus().isOk() - .expectBody(String.class).isEqualTo(TEST_USER_LOGIN); <%_ } _%> } } diff --git a/generators/server/templates/src/test/java/package/web/rest/AccountResourceIT_skipUserManagement.java.ejs b/generators/server/templates/src/test/java/package/web/rest/AccountResourceIT_skipUserManagement.java.ejs index 1dcb458175a..32d260738ce 100644 --- a/generators/server/templates/src/test/java/package/web/rest/AccountResourceIT_skipUserManagement.java.ejs +++ b/generators/server/templates/src/test/java/package/web/rest/AccountResourceIT_skipUserManagement.java.ejs @@ -31,10 +31,10 @@ import org.junit.jupiter.api.Test; import <%= packageName %>.ReactiveSqlTestContainerExtension; <%_ } _%> import org.springframework.beans.factory.annotation.Autowired; -<%_ if (!reactive) { _%> -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -<%_ } else { _%> +<%_ if (reactive) { _%> import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; +<%_ } else { _%> +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; <%_ } _%> import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; @@ -56,10 +56,10 @@ import static <%= packageName %>.web.rest.AccountResourceIT.TEST_USER_LOGIN; /** * Integration tests for the {@link AccountResource} REST controller. */ -<%_ if (!reactive) { _%> -@AutoConfigureMockMvc -<%_ } else { _%> +<%_ if (reactive) { _%> @AutoConfigureWebTestClient(timeout = IntegrationTest.DEFAULT_TIMEOUT) +<%_ } else { _%> +@AutoConfigureMockMvc <%_ } _%> @WithMockUser(value = TEST_USER_LOGIN) @IntegrationTest @@ -67,10 +67,10 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan static final String TEST_USER_LOGIN = "test"; @Autowired -<%_ if (!reactive) { _%> - private MockMvc restAccountMockMvc; -<%_ } else { _%> +<%_ if (reactive) { _%> private WebTestClient accountWebTestClient; +<%_ } else { _%> + private MockMvc restAccountMockMvc; <%_ } _%> <%_ if (searchEngineElasticsearch && reactive) { _%> @@ -81,14 +81,7 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan @Test @WithMockUser(username = TEST_USER_LOGIN, authorities = AuthoritiesConstants.ADMIN) void testGetExistingAccount() <% if (!reactive) { %>throws Exception <% } %>{ -<%_ if (!reactive) { _%> - 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)) - .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN)); -<%_ } else { _%> +<%_ if (reactive) { _%> accountWebTestClient.get().uri("/api/account") .accept(MediaType.APPLICATION_JSON) .exchange() @@ -97,30 +90,43 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan .expectBody() .jsonPath("$.login").isEqualTo(TEST_USER_LOGIN) .jsonPath("$.authorities").isEqualTo(AuthoritiesConstants.ADMIN); +<%_ } else { _%> + 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)) + .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN)); <%_ } _%> } @Test @WithUnauthenticatedMockUser -<%_ if (!reactive) { _%> void testNonAuthenticatedUser() <% if (!reactive) { %>throws Exception <% } %>{ - restAccountMockMvc.perform(get("/api/authenticate") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string("")); -<%_ } else { _%> - void testNonAuthenticatedUser() { +<%_ if (reactive) { _%> accountWebTestClient.get().uri("/api/authenticate") .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() .expectBody().isEmpty(); +<%_ } else { _%> + restAccountMockMvc.perform(get("/api/authenticate") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string("")); <%_ } _%> } @Test -<%_ if (!reactive) { _%> void testAuthenticatedUser() <% if (!reactive) { %>throws Exception <% } %>{ +<%_ if (reactive) { _%> + accountWebTestClient + .get().uri("/api/authenticate") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isOk() + .expectBody(String.class).isEqualTo(TEST_USER_LOGIN); +<%_ } else { _%> restAccountMockMvc.perform(get("/api/authenticate") .with(request -> { request.setRemoteUser(TEST_USER_LOGIN); @@ -129,14 +135,6 @@ class AccountResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassan .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(TEST_USER_LOGIN)); -<%_ } else { _%> - void testAuthenticatedUser() { - accountWebTestClient - .get().uri("/api/authenticate") - .accept(MediaType.APPLICATION_JSON) - .exchange() - .expectStatus().isOk() - .expectBody(String.class).isEqualTo(TEST_USER_LOGIN); <%_ } _%> } } diff --git a/generators/server/templates/src/test/java/package/web/rest/KafkaResourceIT.java.ejs b/generators/server/templates/src/test/java/package/web/rest/KafkaResourceIT.java.ejs index e32d730ad1a..1435a60dc8d 100644 --- a/generators/server/templates/src/test/java/package/web/rest/KafkaResourceIT.java.ejs +++ b/generators/server/templates/src/test/java/package/web/rest/KafkaResourceIT.java.ejs @@ -28,12 +28,12 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> +import org.springframework.test.web.reactive.server.WebTestClient; +<%_ } else { _%> import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -<%_ } else { _%> -import org.springframework.test.web.reactive.server.WebTestClient; <%_ } _%> import org.testcontainers.containers.KafkaContainer; import org.testcontainers.utility.DockerImageName; @@ -56,10 +56,10 @@ class <%= upperFirstCamelCase(baseName) %>KafkaResourceIT { private static boolean started = false; private static KafkaContainer kafkaContainer; -<%_ if (!reactive) { _%> - private MockMvc restMockMvc; -<%_ } else { _%> +<%_ if (reactive) { _%> private WebTestClient client; +<%_ } else { _%> + private MockMvc restMockMvc; <%_ } _%> @BeforeAll @@ -89,24 +89,24 @@ class <%= upperFirstCamelCase(baseName) %>KafkaResourceIT { <%= upperFirstCamelCase(baseName) %>KafkaResource kafkaResource = new <%= upperFirstCamelCase(baseName) %>KafkaResource(kafkaProperties); -<%_ if (!reactive) { _%> - restMockMvc = MockMvcBuilders.standaloneSetup(kafkaResource).build(); -<%_ } else { _%> +<%_ if (reactive) { _%> client = WebTestClient.bindToController(kafkaResource).build(); +<%_ } else { _%> + restMockMvc = MockMvcBuilders.standaloneSetup(kafkaResource).build(); <%_ } _%> } @Test void producesMessages()<% if (!reactive) { %> throws Exception<% } %> { -<%_ if (!reactive) { _%> - restMockMvc.perform(post("/api/<%= dasherizedBaseName %>-kafka/publish/topic-produce?message=value-produce")) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)); -<%_ } else { _%> +<%_ if (reactive) { _%> client.post().uri("/api/<%= dasherizedBaseName %>-kafka/publish/topic-produce?message=value-produce") .exchange() .expectStatus().isOk() .expectHeader().contentType(MediaType.APPLICATION_JSON); +<%_ } else { _%> + restMockMvc.perform(post("/api/<%= dasherizedBaseName %>-kafka/publish/topic-produce?message=value-produce")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)); <%_ } _%> Map consumerProps = new HashMap<>(getConsumerProps("group-produce")); @@ -126,7 +126,17 @@ class <%= upperFirstCamelCase(baseName) %>KafkaResourceIT { producer.send(new ProducerRecord<>("topic-consume", "value-consume")); -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + String value = client.get().uri("/api/<%= dasherizedBaseName %>-kafka/consume?topic=topic-consume") + .accept(MediaType.TEXT_EVENT_STREAM) + .exchange() + .expectStatus().isOk() + .expectHeader().contentTypeCompatibleWith(MediaType.TEXT_EVENT_STREAM) + .returnResult(String.class) + .getResponseBody().blockFirst(Duration.ofSeconds(10)); + + assertThat(value).isEqualTo("value-consume"); +<%_ } else { _%> MvcResult mvcResult = restMockMvc.perform(get("/api/<%= dasherizedBaseName %>-kafka/consume?topic=topic-consume")) .andExpect(status().isOk()) .andExpect(request().asyncStarted()) @@ -140,16 +150,6 @@ class <%= upperFirstCamelCase(baseName) %>KafkaResourceIT { } } fail("Expected content data:value-consume not received"); -<%_ } else { _%> - String value = client.get().uri("/api/<%= dasherizedBaseName %>-kafka/consume?topic=topic-consume") - .accept(MediaType.TEXT_EVENT_STREAM) - .exchange() - .expectStatus().isOk() - .expectHeader().contentTypeCompatibleWith(MediaType.TEXT_EVENT_STREAM) - .returnResult(String.class) - .getResponseBody().blockFirst(Duration.ofSeconds(10)); - - assertThat(value).isEqualTo("value-consume"); <%_ } _%> } diff --git a/generators/server/templates/src/test/java/package/web/rest/LogoutResourceIT.java.ejs b/generators/server/templates/src/test/java/package/web/rest/LogoutResourceIT.java.ejs index 4dc49137bb5..5e48bbfb8fc 100644 --- a/generators/server/templates/src/test/java/package/web/rest/LogoutResourceIT.java.ejs +++ b/generators/server/templates/src/test/java/package/web/rest/LogoutResourceIT.java.ejs @@ -22,11 +22,11 @@ package <%= packageName %>.web.rest; import static <%= packageName %>.test.util.OAuth2TestUtil.ID_TOKEN; import static <%= packageName %>.test.util.OAuth2TestUtil.authenticationToken; import static <%= packageName %>.test.util.OAuth2TestUtil.registerAuthenticationToken; -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> +import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.*; +<%_ } else { _%> import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; -<%_ } else { _%> -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.*; <%_ } _%> import <%= packageName %>.IntegrationTest; @@ -39,15 +39,15 @@ import org.springframework.http.MediaType; import org.springframework.security.oauth2.client.<% if (reactive) { %>Reactive<% } %>OAuth2AuthorizedClientService; import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.client.registration.<% if (reactive) { %>Reactive<% } %>ClientRegistrationRepository; -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> +import org.springframework.context.ApplicationContext; +import org.springframework.test.web.reactive.server.WebTestClient; +<%_ } else { _%> import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -<%_ } else { _%> -import org.springframework.context.ApplicationContext; -import org.springframework.test.web.reactive.server.WebTestClient; <%_ } _%> import java.util.Collections; @@ -72,10 +72,10 @@ class LogoutResourceIT { @Autowired private ClientRegistration clientRegistration; -<%_ if (!reactive) { _%> - private MockMvc restLogoutMockMvc; -<%_ } else { _%> +<%_ if (reactive) { _%> private WebTestClient webTestClient; +<%_ } else { _%> + private MockMvc restLogoutMockMvc; <%_ } _%> private Map claims; @@ -86,7 +86,12 @@ class LogoutResourceIT { claims.put("groups", Collections.singletonList(AuthoritiesConstants.USER)); claims.put("sub", 123); -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + this.webTestClient = WebTestClient.bindToApplicationContext(this.context) + .apply(springSecurity()) + .configureClient() + .build(); +<%_ } else { _%> SecurityContextHolder .getContext() .setAuthentication(registerAuthenticationToken(authorizedClientService, clientRegistration, authenticationToken(claims))); @@ -94,26 +99,13 @@ class LogoutResourceIT { authInjector.afterPropertiesSet(); this.restLogoutMockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); -<%_ } else { _%> - this.webTestClient = WebTestClient.bindToApplicationContext(this.context) - .apply(springSecurity()) - .configureClient() - .build(); <%_ } _%> } @Test void getLogoutInformation() <% if (!reactive) { %>throws Exception <% } %>{ final String ORIGIN_URL = "http://localhost:8080"; -<%_ if (!reactive) { _%> - String logoutUrl = this.registrations.findByRegistrationId("oidc").getProviderDetails() - .getConfigurationMetadata().get("end_session_endpoint").toString(); - logoutUrl = logoutUrl + "?id_token_hint=" + ID_TOKEN + "&post_logout_redirect_uri=" + ORIGIN_URL; - restLogoutMockMvc.perform(post("http://localhost:8080/api/logout").header(HttpHeaders.ORIGIN, ORIGIN_URL)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) - .andExpect(jsonPath("$.logoutUrl").value(logoutUrl)); -<%_ } else { _%> +<%_ if (reactive) { _%> String logoutUrl = this.registrations.findByRegistrationId("oidc") .map(oidc -> oidc.getProviderDetails().getConfigurationMetadata() .get("end_session_endpoint").toString()).block(); @@ -125,6 +117,14 @@ class LogoutResourceIT { .expectHeader().contentType(MediaType.APPLICATION_JSON_VALUE) .expectBody() .jsonPath("$.logoutUrl").isEqualTo(logoutUrl); +<%_ } else { _%> + String logoutUrl = this.registrations.findByRegistrationId("oidc").getProviderDetails() + .getConfigurationMetadata().get("end_session_endpoint").toString(); + logoutUrl = logoutUrl + "?id_token_hint=" + ID_TOKEN + "&post_logout_redirect_uri=" + ORIGIN_URL; + restLogoutMockMvc.perform(post("http://localhost:8080/api/logout").header(HttpHeaders.ORIGIN, ORIGIN_URL)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.logoutUrl").value(logoutUrl)); <%_ } _%> } } diff --git a/generators/server/templates/src/test/java/package/web/rest/PublicUserResourceIT.java.ejs b/generators/server/templates/src/test/java/package/web/rest/PublicUserResourceIT.java.ejs index ab9582b2adf..dc0fbcd2d15 100644 --- a/generators/server/templates/src/test/java/package/web/rest/PublicUserResourceIT.java.ejs +++ b/generators/server/templates/src/test/java/package/web/rest/PublicUserResourceIT.java.ejs @@ -40,10 +40,10 @@ import <%= packageName %>.service.EntityManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -<%_ if (!reactive) { _%> -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -<%_ } else { _%> +<%_ if (reactive) { _%> import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; +<%_ } else { _%> +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; <%_ } _%> <%_ if (cacheManagerIsAvailable) { _%> import org.springframework.cache.CacheManager; @@ -60,8 +60,7 @@ import org.springframework.security.test.context.support.WithMockUser; <%_ if (reactive) { _%> import <%= packageName %>.service.dto.<%= asDto('User') %>; import org.springframework.test.web.reactive.server.WebTestClient; -<%_ } _%> -<%_ if (!reactive) { _%> +<%_ } else { _%> import org.springframework.test.web.servlet.MockMvc; <%_ } _%> <%_ if (databaseTypeSql && !reactive) { _%> @@ -88,24 +87,24 @@ import static org.assertj.core.api.Assertions.assertThat; <%_ if (reactive && searchEngineElasticsearch) { _%> import static org.mockito.Mockito.*; <%_ } _%> -<%_ if (!reactive) { _%> +<%_ if (reactive && testsNeedCsrf) { _%> +import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf; +<%_ } else if (!reactive) { _%> <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) { _%> import static org.hamcrest.Matchers.hasItems; <%_ } _%> import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; -<%_ } else if (testsNeedCsrf) { _%> -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf; <%_ } _%> /** * Integration tests for the {@link UserResource} REST controller. */ -<%_ if (!reactive) { _%> -@AutoConfigureMockMvc -<%_ } else { _%> +<%_ if (reactive) { _%> @AutoConfigureWebTestClient(timeout = IntegrationTest.DEFAULT_TIMEOUT) +<%_ } else { _%> +@AutoConfigureMockMvc <%_ } _%> @WithMockUser(authorities = AuthoritiesConstants.ADMIN) @IntegrationTest @@ -179,7 +178,19 @@ class PublicUserResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCas userRepository.<% if (databaseTypeSql && reactive && authenticationTypeOauth2) { %>create<% } else { %>save<% } %><% if (databaseTypeSql && !reactive) { %>AndFlush<% } %>(user)<% if (reactive) { %>.block()<% } %>; // Get all the users -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> + <%= asDto('User') %> foundUser = webTestClient.get().uri("/api/users?sort=id,DESC") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isOk() + .expectHeader().contentType(MediaType.APPLICATION_JSON) + .returnResult(<%= asDto('User') %>.class).getResponseBody().blockFirst(); + + assertThat(foundUser.getLogin()).isEqualTo(DEFAULT_LOGIN); + <%_ for (field of user.fields.filter(field => !field.builtIn && field.relatedByOtherEntity)) { _%> + assertThat(foundUser.get<%= javaBeanCase(field.fieldName) %>()).isEqualTo(DEFAULT_<%= field.fieldName.toUpperCase() %>); + <%_ } _%> +<%_ } else { _%> restUserMockMvc.perform(get("/api/users<% if (databaseTypeSql) { %>?sort=id,desc<% } %>") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) @@ -193,18 +204,6 @@ class PublicUserResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCas .andExpect(jsonPath("$.[*].imageUrl").doesNotExist()) <%_ } _%> .andExpect(jsonPath("$.[*].langKey").doesNotExist()); -<%_ } else { _%> - <%= asDto('User') %> foundUser = webTestClient.get().uri("/api/users?sort=id,DESC") - .accept(MediaType.APPLICATION_JSON) - .exchange() - .expectStatus().isOk() - .expectHeader().contentType(MediaType.APPLICATION_JSON) - .returnResult(<%= asDto('User') %>.class).getResponseBody().blockFirst(); - - assertThat(foundUser.getLogin()).isEqualTo(DEFAULT_LOGIN); - <%_ for (field of user.fields.filter(field => !field.builtIn && field.relatedByOtherEntity)) { _%> - assertThat(foundUser.get<%= javaBeanCase(field.fieldName) %>()).isEqualTo(DEFAULT_<%= field.fieldName.toUpperCase() %>); - <%_ } _%> <% } _%> } @@ -215,15 +214,7 @@ class PublicUserResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCas @Transactional <%_ } _%> void getAllAuthorities()<% if (!reactive) { %> throws Exception<% } %> { - <%_ if (!reactive) { _%> - restUserMockMvc.perform(get("/api/authorities") - .accept(MediaType.APPLICATION_JSON) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) - .andExpect(jsonPath("$").isArray()) - .andExpect(jsonPath("$").value(hasItems(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN))); - <%_ } else { _%> + <%_ if (reactive) { _%> webTestClient.get().uri("/api/authorities") .accept(MediaType.APPLICATION_JSON) .exchange() @@ -233,6 +224,14 @@ class PublicUserResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCas .jsonPath("$").isArray() .jsonPath("$[?(@=='" + AuthoritiesConstants.ADMIN + "')]").hasJsonPath() .jsonPath("$[?(@=='" + AuthoritiesConstants.USER + "')]").hasJsonPath(); + <%_ } else { _%> + restUserMockMvc.perform(get("/api/authorities") + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$").isArray()) + .andExpect(jsonPath("$").value(hasItems(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN))); <%_ } _%> } <%_ } _%> @@ -246,16 +245,16 @@ class PublicUserResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCas // Initialize the database userRepository.<% if (reactive) { %>save<% } else { %>saveAndFlush<% } %>(user)<% if (reactive) { %>.block()<% } %>; - <%_ if (!reactive) { _%> - restUserMockMvc.perform(get("/api/users?sort=resetKey,desc").accept(MediaType.APPLICATION_JSON)).andExpect(status().isBadRequest()); - restUserMockMvc.perform(get("/api/users?sort=password,desc").accept(MediaType.APPLICATION_JSON)).andExpect(status().isBadRequest()); - restUserMockMvc.perform(get("/api/users?sort=resetKey,id,desc").accept(MediaType.APPLICATION_JSON)).andExpect(status().isBadRequest()); - restUserMockMvc.perform(get("/api/users?sort=id,desc").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); - <%_ } else { _%> + <%_ if (reactive) { _%> webTestClient.get().uri("/api/users?sort=resetKey,DESC").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isBadRequest(); webTestClient.get().uri("/api/users?sort=password,DESC").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isBadRequest(); webTestClient.get().uri("/api/users?sort=resetKey,id,DESC").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isBadRequest(); webTestClient.get().uri("/api/users?sort=id,DESC").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk(); + <%_ } else { _%> + restUserMockMvc.perform(get("/api/users?sort=resetKey,desc").accept(MediaType.APPLICATION_JSON)).andExpect(status().isBadRequest()); + restUserMockMvc.perform(get("/api/users?sort=password,desc").accept(MediaType.APPLICATION_JSON)).andExpect(status().isBadRequest()); + restUserMockMvc.perform(get("/api/users?sort=resetKey,id,desc").accept(MediaType.APPLICATION_JSON)).andExpect(status().isBadRequest()); + restUserMockMvc.perform(get("/api/users?sort=id,desc").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); <%_ } _%> } <%_ } _%> diff --git a/generators/server/templates/src/test/java/package/web/rest/UserJWTControllerIT.java.ejs b/generators/server/templates/src/test/java/package/web/rest/UserJWTControllerIT.java.ejs index 2e99c67d0b0..8000440e2f8 100644 --- a/generators/server/templates/src/test/java/package/web/rest/UserJWTControllerIT.java.ejs +++ b/generators/server/templates/src/test/java/package/web/rest/UserJWTControllerIT.java.ejs @@ -32,10 +32,10 @@ import <%= packageName %>.repository.UserRepository; import <%= packageName %>.web.rest.vm.LoginVM; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -<%_ if (!reactive) { _%> -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -<%_ } else { _%> +<%_ if (reactive) { _%> import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; +<%_ } else { _%> +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; <%_ } _%> import org.springframework.http.MediaType; <%_ if (!skipUserManagement) { _%> @@ -43,8 +43,7 @@ import org.springframework.security.crypto.password.PasswordEncoder; <%_ } _%> <%_ if (reactive) { _%> import org.springframework.test.web.reactive.server.WebTestClient; -<%_ } _%> -<%_ if (!reactive) { _%> +<%_ } else { _%> import org.springframework.test.web.servlet.MockMvc; <%_ if (databaseTypeSql) { _%> import org.springframework.transaction.annotation.Transactional; @@ -69,10 +68,10 @@ import static org.hamcrest.Matchers.not; /** * Integration tests for the {@link UserJWTController} REST controller. */ -<%_ if (!reactive) { _%> -@AutoConfigureMockMvc -<%_ } else { _%> +<%_ if (reactive) { _%> @AutoConfigureWebTestClient(timeout = IntegrationTest.DEFAULT_TIMEOUT) +<%_ } else { _%> +@AutoConfigureMockMvc <%_ } _%> @IntegrationTest class UserJWTControllerIT <% if (databaseTypeCassandra) { %>extends AbstractCassandraTest <% } %>{ @@ -120,16 +119,7 @@ class UserJWTControllerIT <% if (databaseTypeCassandra) { %>extends AbstractCass login.setUsername("test"); <%_ } _%> login.setPassword("test"); -<%_ if (!reactive) { _%> - 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()) - .andExpect(header().string("Authorization", not(nullValue()))) - .andExpect(header().string("Authorization", not(is(emptyString())))); -<%_ } else { _%> +<%_ if (reactive) { _%> webTestClient.post().uri("/api/authenticate") .contentType(MediaType.APPLICATION_JSON) .bodyValue(TestUtil.convertObjectToJsonBytes(login)) @@ -138,6 +128,15 @@ class UserJWTControllerIT <% if (databaseTypeCassandra) { %>extends AbstractCass .expectHeader().valueMatches("Authorization", "Bearer .+") .expectBody() .jsonPath("$.id_token").isNotEmpty(); +<%_ } else { _%> + 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()) + .andExpect(header().string("Authorization", not(nullValue()))) + .andExpect(header().string("Authorization", not(is(emptyString())))); <%_ } _%> } @@ -170,16 +169,7 @@ class UserJWTControllerIT <% if (databaseTypeCassandra) { %>extends AbstractCass <%_ } _%> login.setPassword("test"); login.setRememberMe(true); -<%_ if (!reactive) { _%> - 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()) - .andExpect(header().string("Authorization", not(nullValue()))) - .andExpect(header().string("Authorization", not(is(emptyString())))); -<%_ } else { _%> +<%_ if (reactive) { _%> webTestClient.post().uri("/api/authenticate") .contentType(MediaType.APPLICATION_JSON) .bodyValue(TestUtil.convertObjectToJsonBytes(login)) @@ -188,6 +178,15 @@ class UserJWTControllerIT <% if (databaseTypeCassandra) { %>extends AbstractCass .expectHeader().valueMatches("Authorization", "Bearer .+") .expectBody() .jsonPath("$.id_token").isNotEmpty(); +<%_ } else { _%> + 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()) + .andExpect(header().string("Authorization", not(nullValue()))) + .andExpect(header().string("Authorization", not(is(emptyString())))); <%_ } _%> } @@ -196,14 +195,7 @@ class UserJWTControllerIT <% if (databaseTypeCassandra) { %>extends AbstractCass LoginVM login = new LoginVM(); login.setUsername("wrong-user"); login.setPassword("wrong password"); -<%_ if (!reactive) { _%> - 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")); -<%_ } else { _%> +<%_ if (reactive) { _%> webTestClient.post().uri("/api/authenticate") .contentType(MediaType.APPLICATION_JSON) .bodyValue(TestUtil.convertObjectToJsonBytes(login)) @@ -212,6 +204,13 @@ class UserJWTControllerIT <% if (databaseTypeCassandra) { %>extends AbstractCass .expectHeader().doesNotExist("Authorization") .expectBody() .jsonPath("$.id_token").doesNotExist(); +<%_ } else { _%> + 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/generators/server/templates/src/test/java/package/web/rest/UserResourceIT.java.ejs b/generators/server/templates/src/test/java/package/web/rest/UserResourceIT.java.ejs index a7075200a57..272aec8a71a 100644 --- a/generators/server/templates/src/test/java/package/web/rest/UserResourceIT.java.ejs +++ b/generators/server/templates/src/test/java/package/web/rest/UserResourceIT.java.ejs @@ -50,10 +50,10 @@ import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -<%_ if (!reactive) { _%> -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -<%_ } else { _%> +<%_ if (reactive) { _%> import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; +<%_ } else { _%> +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; <%_ } _%> <%_ if (cacheManagerIsAvailable) { _%> import org.springframework.cache.CacheManager; @@ -69,8 +69,7 @@ import org.springframework.security.test.context.TestSecurityContextHolder; import org.springframework.security.test.context.support.WithMockUser; <%_ if (reactive) { _%> import org.springframework.test.web.reactive.server.WebTestClient; -<%_ } _%> -<%_ if (!reactive) { _%> +<%_ } else { _%> import org.springframework.test.web.servlet.MockMvc; <%_ } _%> <%_ if (databaseTypeSql && !reactive) { _%> @@ -97,27 +96,27 @@ import static org.assertj.core.api.Assertions.assertThat; <%_ if (reactive && searchEngineElasticsearch) { _%> import static org.mockito.Mockito.*; <%_ } _%> -<%_ if (!reactive) { _%> - <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) { _%> +<%_ if (reactive && testsNeedCsrf) { _%> +import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf; +<%_ } else if (!reactive) { _%> + <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) { _%> import static org.hamcrest.Matchers.hasItems; - <%_ } _%> + <%_ } _%> import static org.hamcrest.Matchers.hasItem; - <%_ if (testsNeedCsrf) { _%> + <%_ if (testsNeedCsrf) { _%> import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; - <%_ } _%> + <%_ } _%> import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; -<%_ } else if (testsNeedCsrf) { _%> -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf; <%_ } _%> /** * Integration tests for the {@link UserResource} REST controller. */ -<%_ if (!reactive) { _%> -@AutoConfigureMockMvc -<%_ } else { _%> +<%_ if (reactive) { _%> @AutoConfigureWebTestClient(timeout = IntegrationTest.DEFAULT_TIMEOUT) +<%_ } else { _%> +@AutoConfigureMockMvc <%_ } _%> @WithMockUser(authorities = AuthoritiesConstants.ADMIN) @IntegrationTest @@ -315,18 +314,18 @@ class UserResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassandra managedUserVM.setLangKey(DEFAULT_LANGKEY); managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - <%_ if (!reactive) { _%> - restUserMockMvc.perform(post("/api/admin/users") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))<% if (testsNeedCsrf) { %> - .with(csrf())<% } %>) - .andExpect(status().isCreated()); - <%_ } else { _%> + <%_ if (reactive) { _%> webTestClient.post().uri("/api/admin/users") .contentType(MediaType.APPLICATION_JSON) .bodyValue(TestUtil.convertObjectToJsonBytes(managedUserVM)) .exchange() .expectStatus().isCreated(); + <%_ } else { _%> + restUserMockMvc.perform(post("/api/admin/users") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))<% if (testsNeedCsrf) { %> + .with(csrf())<% } %>) + .andExpect(status().isCreated()); <%_ } _%> // Validate the User in the database @@ -373,18 +372,18 @@ class UserResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassandra managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); // An entity with an existing ID cannot be created, so this API call must fail - <%_ if (!reactive) { _%> - restUserMockMvc.perform(post("/api/admin/users") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))<% if (testsNeedCsrf) { %> - .with(csrf())<% } %>) - .andExpect(status().isBadRequest()); - <%_ } else { _%> + <%_ if (reactive) { _%> webTestClient.post().uri("/api/admin/users") .contentType(MediaType.APPLICATION_JSON) .bodyValue(TestUtil.convertObjectToJsonBytes(managedUserVM)) .exchange() .expectStatus().isBadRequest(); + <%_ } else { _%> + restUserMockMvc.perform(post("/api/admin/users") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))<% if (testsNeedCsrf) { %> + .with(csrf())<% } %>) + .andExpect(status().isBadRequest()); <%_ } _%> // Validate the User in the database @@ -418,18 +417,18 @@ class UserResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassandra managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); // Create the User - <%_ if (!reactive) { _%> - restUserMockMvc.perform(post("/api/admin/users") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))<% if (testsNeedCsrf) { %> - .with(csrf())<% } %>) - .andExpect(status().isBadRequest()); - <%_ } else { _%> + <%_ if (reactive) { _%> webTestClient.post().uri("/api/admin/users") .contentType(MediaType.APPLICATION_JSON) .bodyValue(TestUtil.convertObjectToJsonBytes(managedUserVM)) .exchange() .expectStatus().isBadRequest(); + <%_ } else { _%> + restUserMockMvc.perform(post("/api/admin/users") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))<% if (testsNeedCsrf) { %> + .with(csrf())<% } %>) + .andExpect(status().isBadRequest()); <%_ } _%> // Validate the User in the database @@ -463,18 +462,18 @@ class UserResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassandra managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); // Create the User - <%_ if (!reactive) { _%> - restUserMockMvc.perform(post("/api/admin/users") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))<% if (testsNeedCsrf) { %> - .with(csrf())<% } %>) - .andExpect(status().isBadRequest()); - <%_ } else { _%> + <%_ if (reactive) { _%> webTestClient.post().uri("/api/admin/users") .contentType(MediaType.APPLICATION_JSON) .bodyValue(TestUtil.convertObjectToJsonBytes(managedUserVM)) .exchange() .expectStatus().isBadRequest(); + <%_ } else { _%> + restUserMockMvc.perform(post("/api/admin/users") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))<% if (testsNeedCsrf) { %> + .with(csrf())<% } %>) + .andExpect(status().isBadRequest()); <%_ } _%> // Validate the User in the database @@ -497,20 +496,7 @@ class UserResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassandra <%_ } _%> // Get all the users -<%_ if (!reactive) { _%> - restUserMockMvc.perform(get("/api/admin/users<% if (databaseTypeSql) { %>?sort=id,desc<% } %>") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) - .andExpect(jsonPath("$.[*].login").value(hasItem(DEFAULT_LOGIN))) - .andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRSTNAME))) - .andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LASTNAME))) - .andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL))) - <%_ if (!databaseTypeCassandra) { _%> - .andExpect(jsonPath("$.[*].imageUrl").value(hasItem(DEFAULT_IMAGEURL))) - <%_ } _%> - .andExpect(jsonPath("$.[*].langKey").value(hasItem(DEFAULT_LANGKEY))); -<%_ } else { _%> +<%_ if (reactive) { _%> <%= asDto('AdminUser') %> foundUser = webTestClient.get().uri("/api/admin/users?sort=id,DESC") .accept(MediaType.APPLICATION_JSON) .exchange() @@ -529,6 +515,19 @@ class UserResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassandra <%_ if (databaseTypeSql && !applicationTypeMicroservice) { _%> assertThat(foundUser.getAuthorities()).containsExactly(AuthoritiesConstants.USER); <%_ } _%> +<%_ } else { _%> + restUserMockMvc.perform(get("/api/admin/users<% if (databaseTypeSql) { %>?sort=id,desc<% } %>") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.[*].login").value(hasItem(DEFAULT_LOGIN))) + .andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRSTNAME))) + .andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LASTNAME))) + .andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL))) + <%_ if (!databaseTypeCassandra) { _%> + .andExpect(jsonPath("$.[*].imageUrl").value(hasItem(DEFAULT_IMAGEURL))) + <%_ } _%> + .andExpect(jsonPath("$.[*].langKey").value(hasItem(DEFAULT_LANGKEY))); <%_ } _%> } @@ -555,19 +554,7 @@ class UserResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassandra <%_ } _%> // Get the user -<%_ if (!reactive) { _%> - restUserMockMvc.perform(get("/api/admin/users/{login}", user.getLogin())) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) - .andExpect(jsonPath("$.login").value(user.getLogin())) - .andExpect(jsonPath("$.firstName").value(DEFAULT_FIRSTNAME)) - .andExpect(jsonPath("$.lastName").value(DEFAULT_LASTNAME)) - .andExpect(jsonPath("$.email").value(DEFAULT_EMAIL)) - <%_ if (!databaseTypeCassandra) { _%> - .andExpect(jsonPath("$.imageUrl").value(DEFAULT_IMAGEURL)) - <%_ } _%> - .andExpect(jsonPath("$.langKey").value(DEFAULT_LANGKEY)); -<%_ } else { _%> +<%_ if (reactive) { _%> webTestClient.get().uri("/api/admin/users/{login}", user.getLogin()) .exchange() .expectStatus().isOk() @@ -586,6 +573,18 @@ class UserResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassandra .jsonPath("$.authorities") .isEqualTo(AuthoritiesConstants.USER); <% } %> +<%_ } else { _%> + restUserMockMvc.perform(get("/api/admin/users/{login}", user.getLogin())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.login").value(user.getLogin())) + .andExpect(jsonPath("$.firstName").value(DEFAULT_FIRSTNAME)) + .andExpect(jsonPath("$.lastName").value(DEFAULT_LASTNAME)) + .andExpect(jsonPath("$.email").value(DEFAULT_EMAIL)) + <%_ if (!databaseTypeCassandra) { _%> + .andExpect(jsonPath("$.imageUrl").value(DEFAULT_IMAGEURL)) + <%_ } _%> + .andExpect(jsonPath("$.langKey").value(DEFAULT_LANGKEY)); <%_ } _%> <%_ if (cacheProviderMemcached) { _%> @@ -602,13 +601,13 @@ class UserResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassandra @Transactional <%_ } _%> void getNonExistingUser()<% if (!reactive) { %> throws Exception<% } %> { -<%_ if (!reactive) { _%> - restUserMockMvc.perform(get("/api/admin/users/unknown")) - .andExpect(status().isNotFound()); -<%_ } else { _%> +<%_ if (reactive) { _%> webTestClient.get().uri("/api/admin/users/unknown") .exchange() .expectStatus().isNotFound(); +<%_ } else { _%> + restUserMockMvc.perform(get("/api/admin/users/unknown")) + .andExpect(status().isNotFound()); <%_ } _%> } <%_ if (!authenticationTypeOauth2) { _%> @@ -651,18 +650,18 @@ class UserResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassandra <%_ } _%> managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - <%_ if (!reactive) { _%> - restUserMockMvc.perform(put("/api/admin/users") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))<% if (testsNeedCsrf) { %> - .with(csrf())<% } %>) - .andExpect(status().isOk()); - <%_ } else { _%> + <%_ if (reactive) { _%> webTestClient.put().uri("/api/admin/users") .contentType(MediaType.APPLICATION_JSON) .bodyValue(TestUtil.convertObjectToJsonBytes(managedUserVM)) .exchange() .expectStatus().isOk(); + <%_ } else { _%> + restUserMockMvc.perform(put("/api/admin/users") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))<% if (testsNeedCsrf) { %> + .with(csrf())<% } %>) + .andExpect(status().isOk()); <%_ } _%> // Validate the User in the database @@ -717,18 +716,18 @@ class UserResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassandra <%_ } _%> managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - <%_ if (!reactive) { _%> - restUserMockMvc.perform(put("/api/admin/users") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))<% if (testsNeedCsrf) { %> - .with(csrf())<% } %>) - .andExpect(status().isOk()); - <%_ } else { _%> + <%_ if (reactive) { _%> webTestClient.put().uri("/api/admin/users") .contentType(MediaType.APPLICATION_JSON) .bodyValue(TestUtil.convertObjectToJsonBytes(managedUserVM)) .exchange() .expectStatus().isOk(); + <%_ } else { _%> + restUserMockMvc.perform(put("/api/admin/users") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))<% if (testsNeedCsrf) { %> + .with(csrf())<% } %>) + .andExpect(status().isOk()); <%_ } _%> // Validate the User in the database @@ -802,18 +801,18 @@ class UserResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassandra <%_ } _%> managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - <%_ if (!reactive) { _%> - restUserMockMvc.perform(put("/api/admin/users") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))<% if (testsNeedCsrf) { %> - .with(csrf())<% } %>) - .andExpect(status().isBadRequest()); - <%_ } else { _%> + <%_ if (reactive) { _%> webTestClient.put().uri("/api/admin/users") .contentType(MediaType.APPLICATION_JSON) .bodyValue(TestUtil.convertObjectToJsonBytes(managedUserVM)) .exchange() .expectStatus().isBadRequest(); + <%_ } else { _%> + restUserMockMvc.perform(put("/api/admin/users") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))<% if (testsNeedCsrf) { %> + .with(csrf())<% } %>) + .andExpect(status().isBadRequest()); <%_ } _%> } @@ -873,18 +872,18 @@ class UserResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassandra <%_ } _%> managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - <%_ if (!reactive) { _%> - restUserMockMvc.perform(put("/api/admin/users") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))<% if (testsNeedCsrf) { %> - .with(csrf())<% } %>) - .andExpect(status().isBadRequest()); - <%_ } else { _%> + <%_ if (reactive) { _%> webTestClient.put().uri("/api/admin/users") .contentType(MediaType.APPLICATION_JSON) .bodyValue(TestUtil.convertObjectToJsonBytes(managedUserVM)) .exchange() .expectStatus().isBadRequest(); + <%_ } else { _%> + restUserMockMvc.perform(put("/api/admin/users") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))<% if (testsNeedCsrf) { %> + .with(csrf())<% } %>) + .andExpect(status().isBadRequest()); <%_ } _%> } @@ -903,16 +902,16 @@ class UserResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassandra .collectList().block()<% } %>.size(); // Delete the user - <%_ if (!reactive) { _%> - restUserMockMvc.perform(delete("/api/admin/users/{login}", user.getLogin()) - .accept(MediaType.APPLICATION_JSON)<% if (testsNeedCsrf) { %> - .with(csrf())<% } %>) - .andExpect(status().isNoContent()); - <%_ } else { _%> + <%_ if (reactive) { _%> webTestClient.delete().uri("/api/admin/users/{login}", user.getLogin()) .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isNoContent(); + <%_ } else { _%> + restUserMockMvc.perform(delete("/api/admin/users/{login}", user.getLogin()) + .accept(MediaType.APPLICATION_JSON)<% if (testsNeedCsrf) { %> + .with(csrf())<% } %>) + .andExpect(status().isNoContent()); <%_ } _%> <%_ if (cacheManagerIsAvailable) { _%> diff --git a/generators/server/templates/src/test/java/package/web/rest/errors/ExceptionTranslatorIT.java.ejs b/generators/server/templates/src/test/java/package/web/rest/errors/ExceptionTranslatorIT.java.ejs index 6c3a6474129..0c7d60c2b0f 100644 --- a/generators/server/templates/src/test/java/package/web/rest/errors/ExceptionTranslatorIT.java.ejs +++ b/generators/server/templates/src/test/java/package/web/rest/errors/ExceptionTranslatorIT.java.ejs @@ -26,116 +26,6 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.security.test.context.support.WithMockUser; -<%_ if (!reactive) { _%> -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.http.MediaType; -import org.springframework.test.web.servlet.MockMvc; - -<%_ if (testsNeedCsrf) { _%> -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; -<%_ } _%> -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.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -/** - * Integration tests {@link ExceptionTranslator} controller advice. - */ -@WithMockUser -@AutoConfigureMockMvc -@IntegrationTest -class ExceptionTranslatorIT <% if (databaseTypeCassandra) { %>extends AbstractCassandraTest <% } %>{ - - @Autowired - private MockMvc mockMvc; -<%_ if (!databaseTypeNo && !databaseTypeCassandra) { _%> - - @Test - void testConcurrencyFailure() throws Exception { - mockMvc.perform(get("/api/exception-translator-test/concurrency-failure")<% if (testsNeedCsrf) { %>.with(csrf())<% } %>) - .andExpect(status().isConflict()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_CONCURRENCY_FAILURE)); - } -<%_ } _%> - - @Test - void testMethodArgumentNotValid() throws Exception { - mockMvc.perform(post("/api/exception-translator-test/method-argument").content("{}").contentType(MediaType.APPLICATION_JSON)<% if (testsNeedCsrf) { %>.with(csrf())<% } %>) - .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("must not be null")); - } - - @Test - void testMissingServletRequestPartException() throws Exception { - mockMvc.perform(get("/api/exception-translator-test/missing-servlet-request-part")<% if (testsNeedCsrf) { %>.with(csrf())<% } %>) - .andExpect(status().isBadRequest()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.400")); - } - - @Test - void testMissingServletRequestParameterException() throws Exception { - mockMvc.perform(get("/api/exception-translator-test/missing-servlet-request-parameter")<% if (testsNeedCsrf) { %>.with(csrf())<% } %>) - .andExpect(status().isBadRequest()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.400")); - } - - @Test - void testAccessDenied() throws Exception { - mockMvc.perform(get("/api/exception-translator-test/access-denied")<% if (testsNeedCsrf) { %>.with(csrf())<% } %>) - .andExpect(status().isForbidden()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.403")) - .andExpect(jsonPath("$.detail").value("test access denied!")); - } - - @Test - void testUnauthorized() throws Exception { - mockMvc.perform(get("/api/exception-translator-test/unauthorized")<% if (testsNeedCsrf) { %>.with(csrf())<% } %>) - .andExpect(status().isUnauthorized()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.401")) - .andExpect(jsonPath("$.path").value("/api/exception-translator-test/unauthorized")) - .andExpect(jsonPath("$.detail").value("test authentication failed!")); - } - - @Test - void testMethodNotSupported() throws Exception { - mockMvc.perform(post("/api/exception-translator-test/access-denied")<% if (testsNeedCsrf) { %>.with(csrf())<% } %>) - .andExpect(status().isMethodNotAllowed()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.405")) - .andExpect(jsonPath("$.detail").value("Request method 'POST' not supported")); - } - - @Test - void testExceptionWithResponseStatus() throws Exception { - mockMvc.perform(get("/api/exception-translator-test/response-status")<% if (testsNeedCsrf) { %>.with(csrf())<% } %>) - .andExpect(status().isBadRequest()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.400")) - .andExpect(jsonPath("$.title").value("test response status")); - } - - @Test - void testInternalServerError() throws Exception { - mockMvc.perform(get("/api/exception-translator-test/internal-server-error")<% if (testsNeedCsrf) { %>.with(csrf())<% } %>) - .andExpect(status().isInternalServerError()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.500")) - .andExpect(jsonPath("$.title").value("Internal Server Error")); - } - -} -<%_ } _%> <%_ if (reactive) { _%> <%_ if (testsNeedCsrf) { _%> import org.junit.jupiter.api.BeforeEach; @@ -269,5 +159,114 @@ class ExceptionTranslatorIT <% if (databaseTypeCassandra) { %>extends AbstractCa .jsonPath("$.title").isEqualTo("Internal Server Error"); } +} +<%_ } else { _%> +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; + + <%_ if (testsNeedCsrf) { _%> +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; + <%_ } _%> +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.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** + * Integration tests {@link ExceptionTranslator} controller advice. + */ +@WithMockUser +@AutoConfigureMockMvc +@IntegrationTest +class ExceptionTranslatorIT <% if (databaseTypeCassandra) { %>extends AbstractCassandraTest <% } %>{ + + @Autowired + private MockMvc mockMvc; + <%_ if (!databaseTypeNo && !databaseTypeCassandra) { _%> + + @Test + void testConcurrencyFailure() throws Exception { + mockMvc.perform(get("/api/exception-translator-test/concurrency-failure")<% if (testsNeedCsrf) { %>.with(csrf())<% } %>) + .andExpect(status().isConflict()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_CONCURRENCY_FAILURE)); + } + <%_ } _%> + + @Test + void testMethodArgumentNotValid() throws Exception { + mockMvc.perform(post("/api/exception-translator-test/method-argument").content("{}").contentType(MediaType.APPLICATION_JSON)<% if (testsNeedCsrf) { %>.with(csrf())<% } %>) + .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("must not be null")); + } + + @Test + void testMissingServletRequestPartException() throws Exception { + mockMvc.perform(get("/api/exception-translator-test/missing-servlet-request-part")<% if (testsNeedCsrf) { %>.with(csrf())<% } %>) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.400")); + } + + @Test + void testMissingServletRequestParameterException() throws Exception { + mockMvc.perform(get("/api/exception-translator-test/missing-servlet-request-parameter")<% if (testsNeedCsrf) { %>.with(csrf())<% } %>) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.400")); + } + + @Test + void testAccessDenied() throws Exception { + mockMvc.perform(get("/api/exception-translator-test/access-denied")<% if (testsNeedCsrf) { %>.with(csrf())<% } %>) + .andExpect(status().isForbidden()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.403")) + .andExpect(jsonPath("$.detail").value("test access denied!")); + } + + @Test + void testUnauthorized() throws Exception { + mockMvc.perform(get("/api/exception-translator-test/unauthorized")<% if (testsNeedCsrf) { %>.with(csrf())<% } %>) + .andExpect(status().isUnauthorized()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.401")) + .andExpect(jsonPath("$.path").value("/api/exception-translator-test/unauthorized")) + .andExpect(jsonPath("$.detail").value("test authentication failed!")); + } + + @Test + void testMethodNotSupported() throws Exception { + mockMvc.perform(post("/api/exception-translator-test/access-denied")<% if (testsNeedCsrf) { %>.with(csrf())<% } %>) + .andExpect(status().isMethodNotAllowed()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.405")) + .andExpect(jsonPath("$.detail").value("Request method 'POST' not supported")); + } + + @Test + void testExceptionWithResponseStatus() throws Exception { + mockMvc.perform(get("/api/exception-translator-test/response-status")<% if (testsNeedCsrf) { %>.with(csrf())<% } %>) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.400")) + .andExpect(jsonPath("$.title").value("test response status")); + } + + @Test + void testInternalServerError() throws Exception { + mockMvc.perform(get("/api/exception-translator-test/internal-server-error")<% if (testsNeedCsrf) { %>.with(csrf())<% } %>) + .andExpect(status().isInternalServerError()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.500")) + .andExpect(jsonPath("$.title").value("Internal Server Error")); + } + } <%_ } _%> From 4e36686eb673f80e47ae647689a4b0787392a466 Mon Sep 17 00:00:00 2001 From: Charlie Mordant Date: Sat, 1 Jan 2022 23:30:38 +0100 Subject: [PATCH 2/5] split some files --- .../java/package/common/get_all_template.ejs | 8 +- .../package/service/EntityService.java.ejs | 2 +- .../service/impl/EntityServiceImpl.java.ejs | 2 +- .../__snapshots__/generator.spec.mjs.snap | 63 +++++- generators/server/files.js | 71 ++++++- .../config/LocaleConfiguration.java.ejs | 168 ---------------- .../LocaleConfiguration_reactive.java.ejs | 184 ++++++++++++++++++ .../repository/UserRepository.java.ejs | 4 +- .../DomainUserDetailsService.java.ejs | 2 +- .../java/package/service/UserService.java.ejs | 4 +- .../package/web/rest/AccountResource.java.ejs | 8 +- .../package/web/rest/LogoutResource.java.ejs | 50 +---- .../web/rest/LogoutResource_reactive.java.ejs | 82 ++++++++ .../web/rest/UserJWTController.java.ejs | 3 +- .../security/SecurityUtilsUnitTest.java.ejs | 126 +----------- .../SecurityUtilsUnitTest_reactive.java.ejs | 153 +++++++++++++++ .../errors/ExceptionTranslatorIT.java.ejs | 139 +------------ .../ExceptionTranslatorIT_reactive.java.ejs | 161 +++++++++++++++ 18 files changed, 730 insertions(+), 500 deletions(-) create mode 100644 generators/server/templates/src/main/java/package/config/LocaleConfiguration_reactive.java.ejs create mode 100644 generators/server/templates/src/main/java/package/web/rest/LogoutResource_reactive.java.ejs create mode 100644 generators/server/templates/src/test/java/package/security/SecurityUtilsUnitTest_reactive.java.ejs create mode 100644 generators/server/templates/src/test/java/package/web/rest/errors/ExceptionTranslatorIT_reactive.java.ejs diff --git a/generators/entity-server/templates/src/main/java/package/common/get_all_template.ejs b/generators/entity-server/templates/src/main/java/package/common/get_all_template.ejs index 2bdc0dfd978..a0a15673b14 100644 --- a/generators/entity-server/templates/src/main/java/package/common/get_all_template.ejs +++ b/generators/entity-server/templates/src/main/java/package/common/get_all_template.ejs @@ -69,15 +69,15 @@ _%> log.debug("REST request to get a page of <%= entityClassPlural %>"); <%_ if (reactive) { _%> return <%= entityInstance %><%= viaService ? 'Service.countAll' : 'Repository.count' %>().zipWith(<%= entityInstance %><%= viaService ? 'Service.findAll' : 'Repository.findAllBy' %>(pageable)<%= reactiveEntityToDto %>.collectList()) - .map(countWithEntities -> { - return ResponseEntity.ok() + .map(countWithEntities -> + ResponseEntity.ok() .headers( PaginationUtil.generatePaginationHttpHeaders( UriComponentsBuilder.fromHttpRequest(request), new PageImpl<>(countWithEntities.getT2(), pageable, countWithEntities.getT1()) ) - ).body(countWithEntities.getT2()); - }); + ).body(countWithEntities.getT2()) + ); <%_ } else { _%> <%_ if (relationshipsContainEagerLoad) { _%> Page<<%= instanceType %>> page; diff --git a/generators/entity-server/templates/src/main/java/package/service/EntityService.java.ejs b/generators/entity-server/templates/src/main/java/package/service/EntityService.java.ejs index 63de131ab0a..9c9bd46ebd8 100644 --- a/generators/entity-server/templates/src/main/java/package/service/EntityService.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/service/EntityService.java.ejs @@ -71,7 +71,7 @@ public interface <%= entityClass %>Service { * @param <%= instanceName %> the entity to update partially. * @return the persisted entity. */ - <% if (reactive) { %>Mono<<% } else { %>Optional<<% } %><%= instanceType %>> partialUpdate(<%= instanceType %> <%= instanceName %>); + <% if (reactive) { %>Mono<% } else { %>Optional<% } %><<%= instanceType %>> partialUpdate(<%= instanceType %> <%= instanceName %>); /** * Get all the <%= entityInstancePlural %>. diff --git a/generators/entity-server/templates/src/main/java/package/service/impl/EntityServiceImpl.java.ejs b/generators/entity-server/templates/src/main/java/package/service/impl/EntityServiceImpl.java.ejs index 725c570c335..6787ef12159 100644 --- a/generators/entity-server/templates/src/main/java/package/service/impl/EntityServiceImpl.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/service/impl/EntityServiceImpl.java.ejs @@ -126,7 +126,7 @@ public class <%= serviceClassName %><% if (serviceImpl) { %> implements <%= enti <%_ if (serviceImpl) { _%> @Override <%_ } _%> - public <% if (reactive) { %>Mono<<% } else { %>Optional<<% } %><%= instanceType %>> partialUpdate(<%= instanceType %> <%= instanceName %>) { + public <% if (reactive) { %>Mono<% } else { %>Optional<% } %><<%= instanceType %>> partialUpdate(<%= instanceType %> <%= instanceName %>) { log.debug("Request to partially update <%= entityClass %> : {}", <%= instanceName %>); <%- include('../../common/patch_template', {asEntity, asDto, isService: true, viaService: false}); -%> } diff --git a/generators/server/__snapshots__/generator.spec.mjs.snap b/generators/server/__snapshots__/generator.spec.mjs.snap index 6b962c6dfd9..af4a6777b41 100644 --- a/generators/server/__snapshots__/generator.spec.mjs.snap +++ b/generators/server/__snapshots__/generator.spec.mjs.snap @@ -357,6 +357,7 @@ Object { ], }, Object { + "condition": [Function], "path": "src/test/java/", "templates": Array [ Object { @@ -365,6 +366,16 @@ Object { }, ], }, + Object { + "condition": [Function], + "path": "src/test/java/", + "templates": Array [ + Object { + "file": "package/security/SecurityUtilsUnitTest_reactive.java", + "renameTo": [Function], + }, + ], + }, Object { "condition": [Function], "path": "src/main/java/", @@ -580,10 +591,6 @@ Object { "file": "package/config/JacksonConfiguration.java", "renameTo": [Function], }, - Object { - "file": "package/config/LocaleConfiguration.java", - "renameTo": [Function], - }, Object { "file": "package/config/LoggingAspectConfiguration.java", "renameTo": [Function], @@ -614,6 +621,16 @@ Object { }, ], }, + Object { + "condition": [Function], + "path": "src/main/java/", + "templates": Array [ + Object { + "file": "package/config/LocaleConfiguration.java", + "renameTo": [Function], + }, + ], + }, Object { "condition": [Function], "path": "src/main/java/", @@ -622,6 +639,10 @@ Object { "file": "package/config/ReactorConfiguration.java", "renameTo": [Function], }, + Object { + "file": "package/config/LocaleConfiguration_reactive.java", + "renameTo": [Function], + }, ], }, Object { @@ -767,12 +788,28 @@ Object { "file": "package/web/rest/AuthInfoResource.java", "renameTo": [Function], }, + ], + }, + Object { + "condition": [Function], + "path": "src/main/java/", + "templates": Array [ Object { "file": "package/web/rest/LogoutResource.java", "renameTo": [Function], }, ], }, + Object { + "condition": [Function], + "path": "src/main/java/", + "templates": Array [ + Object { + "file": "package/web/rest/LogoutResource_reactive.java", + "renameTo": [Function], + }, + ], + }, Object { "condition": [Function], "path": "src/main/java/", @@ -1626,12 +1663,28 @@ Object { "file": "package/web/rest/TestUtil.java", "renameTo": [Function], }, + Object { + "file": "package/web/rest/errors/ExceptionTranslatorTestController.java", + "renameTo": [Function], + }, + ], + }, + Object { + "condition": [Function], + "path": "src/test/java/", + "templates": Array [ Object { "file": "package/web/rest/errors/ExceptionTranslatorIT.java", "renameTo": [Function], }, + ], + }, + Object { + "condition": [Function], + "path": "src/test/java/", + "templates": Array [ Object { - "file": "package/web/rest/errors/ExceptionTranslatorTestController.java", + "file": "package/web/rest/errors/ExceptionTranslatorIT_reactive.java", "renameTo": [Function], }, ], diff --git a/generators/server/files.js b/generators/server/files.js index f2b440b54a1..ec6af65cc01 100644 --- a/generators/server/files.js +++ b/generators/server/files.js @@ -457,6 +457,7 @@ const baseServerFiles = { ], }, { + condition: generator => !generator.reactive, path: SERVER_TEST_SRC_DIR, templates: [ { @@ -465,6 +466,16 @@ const baseServerFiles = { }, ], }, + { + condition: generator => generator.reactive, + path: SERVER_TEST_SRC_DIR, + templates: [ + { + file: 'package/security/SecurityUtilsUnitTest_reactive.java', + renameTo: generator => `${generator.testDir}security/SecurityUtilsUnitTest.java`, + }, + ], + }, { condition: generator => generator.authenticationType === JWT, path: SERVER_MAIN_SRC_DIR, @@ -676,12 +687,34 @@ const baseServerFiles = { file: 'package/web/rest/AuthInfoResource.java', renameTo: generator => `${generator.javaDir}web/rest/AuthInfoResource.java`, }, + ], + }, + { + condition: generator => + generator.authenticationType === OAUTH2 && + !generator.reactive && + (generator.applicationType === MONOLITH || generator.applicationType === GATEWAY), + path: SERVER_MAIN_SRC_DIR, + templates: [ { file: 'package/web/rest/LogoutResource.java', renameTo: generator => `${generator.javaDir}web/rest/LogoutResource.java`, }, ], }, + { + condition: generator => + generator.authenticationType === OAUTH2 && + generator.reactive && + (generator.applicationType === MONOLITH || generator.applicationType === GATEWAY), + path: SERVER_MAIN_SRC_DIR, + templates: [ + { + file: 'package/web/rest/LogoutResource_reactive.java', + renameTo: generator => `${generator.javaDir}web/rest/LogoutResource.java`, + }, + ], + }, { condition: generator => generator.applicationType === GATEWAY && generator.serviceDiscoveryType && generator.reactive, path: SERVER_MAIN_SRC_DIR, @@ -840,10 +873,6 @@ const baseServerFiles = { file: 'package/config/JacksonConfiguration.java', renameTo: generator => `${generator.javaDir}config/JacksonConfiguration.java`, }, - { - file: 'package/config/LocaleConfiguration.java', - renameTo: generator => `${generator.javaDir}config/LocaleConfiguration.java`, - }, { file: 'package/config/LoggingAspectConfiguration.java', renameTo: generator => `${generator.javaDir}config/LoggingAspectConfiguration.java`, @@ -866,6 +895,16 @@ const baseServerFiles = { path: SERVER_MAIN_SRC_DIR, templates: [{ file: 'package/config/Constants.java', renameTo: generator => `${generator.javaDir}config/Constants.java` }], }, + { + condition: generator => !generator.reactive, + path: SERVER_MAIN_SRC_DIR, + templates: [ + { + file: 'package/config/LocaleConfiguration.java', + renameTo: generator => `${generator.javaDir}config/LocaleConfiguration.java`, + }, + ], + }, { condition: generator => generator.reactive, path: SERVER_MAIN_SRC_DIR, @@ -874,6 +913,10 @@ const baseServerFiles = { file: 'package/config/ReactorConfiguration.java', renameTo: generator => `${generator.javaDir}config/ReactorConfiguration.java`, }, + { + file: 'package/config/LocaleConfiguration_reactive.java', + renameTo: generator => `${generator.javaDir}config/LocaleConfiguration.java`, + }, ], }, { @@ -1213,13 +1256,29 @@ const baseServerFiles = { path: SERVER_TEST_SRC_DIR, templates: [ { file: 'package/web/rest/TestUtil.java', renameTo: generator => `${generator.testDir}web/rest/TestUtil.java` }, + { + file: 'package/web/rest/errors/ExceptionTranslatorTestController.java', + renameTo: generator => `${generator.testDir}web/rest/errors/ExceptionTranslatorTestController.java`, + }, + ], + }, + { + condition: generator => !generator.reactive, + path: SERVER_TEST_SRC_DIR, + templates: [ { file: 'package/web/rest/errors/ExceptionTranslatorIT.java', renameTo: generator => `${generator.testDir}web/rest/errors/ExceptionTranslatorIT.java`, }, + ], + }, + { + condition: generator => generator.reactive, + path: SERVER_TEST_SRC_DIR, + templates: [ { - file: 'package/web/rest/errors/ExceptionTranslatorTestController.java', - renameTo: generator => `${generator.testDir}web/rest/errors/ExceptionTranslatorTestController.java`, + file: 'package/web/rest/errors/ExceptionTranslatorIT_reactive.java', + renameTo: generator => `${generator.testDir}web/rest/errors/ExceptionTranslatorIT.java`, }, ], }, diff --git a/generators/server/templates/src/main/java/package/config/LocaleConfiguration.java.ejs b/generators/server/templates/src/main/java/package/config/LocaleConfiguration.java.ejs index bff40ee5f67..5a6e05033bb 100644 --- a/generators/server/templates/src/main/java/package/config/LocaleConfiguration.java.ejs +++ b/generators/server/templates/src/main/java/package/config/LocaleConfiguration.java.ejs @@ -18,173 +18,6 @@ -%> package <%= packageName %>.config; -<%_ if (reactive) { _%> -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.context.i18n.LocaleContext; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.context.i18n.SimpleLocaleContext; -import org.springframework.context.i18n.TimeZoneAwareLocaleContext; -import org.springframework.http.HttpCookie; -import org.springframework.http.ResponseCookie; -import org.springframework.http.server.reactive.ServerHttpResponse; -import org.springframework.util.Assert; -import org.springframework.util.StringUtils; -import org.springframework.web.server.ServerWebExchange; -import org.springframework.web.server.WebFilter; -import org.springframework.web.server.i18n.LocaleContextResolver; - -import javax.annotation.Nonnull; -import java.time.Duration; -import java.util.Locale; -import java.util.TimeZone; - -@Configuration -public class LocaleConfiguration { - -@Bean(name = "localeContextResolver") -public LocaleContextResolver localeContextResolver() { -return new AngularCookieLocaleContextResolver(); -} - -@Bean -public WebFilter localeChangeFilter(LocaleContextResolver localeContextResolver) { -return (exchange, chain) -> { -// Find locale change in query param. Must also look form params ? -String newLocale = exchange.getRequest().getQueryParams().getFirst("language"); -if (newLocale != null) { -localeContextResolver.setLocaleContext(exchange, new SimpleLocaleContext(StringUtils.parseLocaleString(newLocale))); -} -// Proceed in any case. -return chain.filter(exchange); -}; -} - -static class AngularCookieLocaleContextResolver implements LocaleContextResolver { - -private static final String LOCALE_REQUEST_ATTRIBUTE_NAME = AngularCookieLocaleContextResolver.class.getName() + ".LOCALE"; - -private static final String TIME_ZONE_REQUEST_ATTRIBUTE_NAME = AngularCookieLocaleContextResolver.class.getName() + ".TIME_ZONE"; - -private static final String QUOTE = "%22"; - -private static final String COOKIE_NAME = "NG_TRANSLATE_LANG_KEY"; - -private static final String COOKIE_PATH = "/"; - -protected final Log logger = LogFactory.getLog(getClass()); - -@Override -@Nonnull -public LocaleContext resolveLocaleContext(@Nonnull ServerWebExchange exchange) { -parseLocaleCookieIfNecessary(exchange); -return new TimeZoneAwareLocaleContext() { -@Override -public Locale getLocale() { -return (Locale) exchange.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME); -} - -@Override -public TimeZone getTimeZone() { -return (TimeZone) exchange.getAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME); -} -}; -} - -@Override -public void setLocaleContext(@Nonnull ServerWebExchange exchange, LocaleContext localeContext) { -Assert.notNull(exchange.getResponse() -, "ServerHttpResponse is required for AngularCookieLocaleContextResolver"); - -Locale locale = null; -TimeZone timeZone = null; -if (localeContext != null) { -locale = localeContext.getLocale(); -if (localeContext instanceof TimeZoneAwareLocaleContext) { -timeZone = ((TimeZoneAwareLocaleContext) localeContext).getTimeZone(); -} -addCookie(exchange.getResponse(), -QUOTE + (locale != null ? locale.toString() : "-") + (timeZone != null ? ' ' + timeZone.getID() : "") + QUOTE); -} -else { -removeCookie(exchange.getResponse()); -} -exchange.getAttributes().put(LOCALE_REQUEST_ATTRIBUTE_NAME, -(locale != null ? locale : LocaleContextHolder.getLocale(exchange.getLocaleContext()))); -if (timeZone != null) { -exchange.getAttributes().put(TIME_ZONE_REQUEST_ATTRIBUTE_NAME, timeZone); -} else { -exchange.getAttributes().remove(TIME_ZONE_REQUEST_ATTRIBUTE_NAME); -} -} - -private void addCookie(@Nonnull ServerHttpResponse response, String cookieValue) { -Assert.notNull(response, "ServerHttpResponse must not be null"); -ResponseCookie cookie = ResponseCookie.from(COOKIE_NAME, cookieValue) -.path(COOKIE_PATH) -.build(); -response.addCookie(cookie); -if (logger.isDebugEnabled()) { -logger.debug("Added cookie with name [" + COOKIE_NAME + "] and value [" + cookieValue + "]"); -} -} - -private void removeCookie(@Nonnull ServerHttpResponse response) { -Assert.notNull(response, "ServerHttpResponse must not be null"); -ResponseCookie cookie = ResponseCookie.from(COOKIE_NAME, "") -.path(COOKIE_PATH) -.maxAge(Duration.ZERO) -.build(); -response.addCookie(cookie); -if (logger.isDebugEnabled()) { -logger.debug("Removed cookie with name [" + COOKIE_NAME + "]"); -} -} - -private void parseLocaleCookieIfNecessary(ServerWebExchange exchange) { -if (exchange.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME) == null) { -// Retrieve and parse cookie value. -HttpCookie cookie = exchange.getRequest().getCookies().getFirst(COOKIE_NAME); -Locale locale = null; -TimeZone timeZone = null; -if (cookie != null) { -String value = cookie.getValue(); - -// Remove the double quote -value = StringUtils.replace(value, QUOTE, ""); - -String localePart = value; -String timeZonePart = null; -int spaceIndex = localePart.indexOf(' '); -if (spaceIndex != -1) { -localePart = value.substring(0, spaceIndex); -timeZonePart = value.substring(spaceIndex + 1); -} -locale = !"-".equals(localePart) ? StringUtils.parseLocaleString(localePart.replace('-', '_')) : null; -if (timeZonePart != null) { -timeZone = StringUtils.parseTimeZoneString(timeZonePart); -} -if (logger.isTraceEnabled()) { -logger.trace("Parsed cookie value [" + cookie.getValue() + "] into locale '" + locale + -"'" + (timeZone != null ? " and time zone '" + timeZone.getID() + "'" : "")); -} -} -if (locale != null) { -exchange.getAttributes().put(LOCALE_REQUEST_ATTRIBUTE_NAME, locale); -} -if (timeZone != null) { -exchange.getAttributes().put(TIME_ZONE_REQUEST_ATTRIBUTE_NAME, timeZone); -} else { -exchange.getAttributes().remove(TIME_ZONE_REQUEST_ATTRIBUTE_NAME); -} -} -} -} -} -<%_ } else { _%> import tech.jhipster.config.locale.AngularCookieLocaleResolver; import org.springframework.context.annotation.Bean; @@ -210,4 +43,3 @@ public class LocaleConfiguration implements WebMvcConfigurer { registry.addInterceptor(localeChangeInterceptor); } } -<%_ } _%> diff --git a/generators/server/templates/src/main/java/package/config/LocaleConfiguration_reactive.java.ejs b/generators/server/templates/src/main/java/package/config/LocaleConfiguration_reactive.java.ejs new file mode 100644 index 00000000000..942e5b5dac5 --- /dev/null +++ b/generators/server/templates/src/main/java/package/config/LocaleConfiguration_reactive.java.ejs @@ -0,0 +1,184 @@ +<%# + Copyright 2013-2021 the original author or authors from the JHipster project. + + This file is part of the JHipster project, see https://www.jhipster.tech/ + for more information. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +-%> +package <%= packageName %>.config; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.context.i18n.LocaleContext; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.context.i18n.SimpleLocaleContext; +import org.springframework.context.i18n.TimeZoneAwareLocaleContext; +import org.springframework.http.HttpCookie; +import org.springframework.http.ResponseCookie; +import org.springframework.http.server.reactive.ServerHttpResponse; +import org.springframework.util.Assert; +import org.springframework.util.StringUtils; +import org.springframework.web.server.ServerWebExchange; +import org.springframework.web.server.WebFilter; +import org.springframework.web.server.i18n.LocaleContextResolver; + +import javax.annotation.Nonnull; +import java.time.Duration; +import java.util.Locale; +import java.util.TimeZone; + +@Configuration +public class LocaleConfiguration { + + @Bean(name = "localeContextResolver") + public LocaleContextResolver localeContextResolver() { + return new AngularCookieLocaleContextResolver(); + } + + @Bean + public WebFilter localeChangeFilter(LocaleContextResolver localeContextResolver) { + return (exchange, chain) -> { + // Find locale change in query param. Must also look form params ? + String newLocale = exchange.getRequest().getQueryParams().getFirst("language"); + if (newLocale != null) { + localeContextResolver.setLocaleContext(exchange, new SimpleLocaleContext(StringUtils.parseLocaleString(newLocale))); + } + // Proceed in any case. + return chain.filter(exchange); + }; + } + + static class AngularCookieLocaleContextResolver implements LocaleContextResolver { + + private static final String LOCALE_REQUEST_ATTRIBUTE_NAME = AngularCookieLocaleContextResolver.class.getName() + ".LOCALE"; + + private static final String TIME_ZONE_REQUEST_ATTRIBUTE_NAME = AngularCookieLocaleContextResolver.class.getName() + ".TIME_ZONE"; + + private static final String QUOTE = "%22"; + + private static final String COOKIE_NAME = "NG_TRANSLATE_LANG_KEY"; + + private static final String COOKIE_PATH = "/"; + + protected final Log logger = LogFactory.getLog(getClass()); + + @Override + @Nonnull + public LocaleContext resolveLocaleContext(@Nonnull ServerWebExchange exchange) { + parseLocaleCookieIfNecessary(exchange); + return new TimeZoneAwareLocaleContext() { + @Override + public Locale getLocale() { + return (Locale) exchange.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME); + } + + @Override + public TimeZone getTimeZone() { + return (TimeZone) exchange.getAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME); + } + }; + } + + @Override + public void setLocaleContext(@Nonnull ServerWebExchange exchange, LocaleContext localeContext) { + Assert.notNull(exchange.getResponse() + , "ServerHttpResponse is required for AngularCookieLocaleContextResolver"); + + Locale locale = null; + TimeZone timeZone = null; + if (localeContext != null) { + locale = localeContext.getLocale(); + if (localeContext instanceof TimeZoneAwareLocaleContext) { + timeZone = ((TimeZoneAwareLocaleContext) localeContext).getTimeZone(); + } + addCookie(exchange.getResponse(), + QUOTE + (locale != null ? locale.toString() : "-") + (timeZone != null ? ' ' + timeZone.getID() : "") + QUOTE); + } else { + removeCookie(exchange.getResponse()); + } + exchange.getAttributes().put(LOCALE_REQUEST_ATTRIBUTE_NAME, + (locale != null ? locale : LocaleContextHolder.getLocale(exchange.getLocaleContext()))); + if (timeZone != null) { + exchange.getAttributes().put(TIME_ZONE_REQUEST_ATTRIBUTE_NAME, timeZone); + } else { + exchange.getAttributes().remove(TIME_ZONE_REQUEST_ATTRIBUTE_NAME); + } + } + + private void addCookie(@Nonnull ServerHttpResponse response, String cookieValue) { + Assert.notNull(response, "ServerHttpResponse must not be null"); + ResponseCookie cookie = ResponseCookie.from(COOKIE_NAME, cookieValue) + .path(COOKIE_PATH) + .build(); + response.addCookie(cookie); + if (logger.isDebugEnabled()) { + logger.debug("Added cookie with name [" + COOKIE_NAME + "] and value [" + cookieValue + "]"); + } + } + + private void removeCookie(@Nonnull ServerHttpResponse response) { + Assert.notNull(response, "ServerHttpResponse must not be null"); + ResponseCookie cookie = ResponseCookie.from(COOKIE_NAME, "") + .path(COOKIE_PATH) + .maxAge(Duration.ZERO) + .build(); + response.addCookie(cookie); + if (logger.isDebugEnabled()) { + logger.debug("Removed cookie with name [" + COOKIE_NAME + "]"); + } + } + + private void parseLocaleCookieIfNecessary(ServerWebExchange exchange) { + if (exchange.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME) == null) { + // Retrieve and parse cookie value. + HttpCookie cookie = exchange.getRequest().getCookies().getFirst(COOKIE_NAME); + Locale locale = null; + TimeZone timeZone = null; + if (cookie != null) { + String value = cookie.getValue(); + + // Remove the double quote + value = StringUtils.replace(value, QUOTE, ""); + + String localePart = value; + String timeZonePart = null; + int spaceIndex = localePart.indexOf(' '); + if (spaceIndex != -1) { + localePart = value.substring(0, spaceIndex); + timeZonePart = value.substring(spaceIndex + 1); + } + locale = !"-".equals(localePart) ? StringUtils.parseLocaleString(localePart.replace('-', '_')) : null; + if (timeZonePart != null) { + timeZone = StringUtils.parseTimeZoneString(timeZonePart); + } + if (logger.isTraceEnabled()) { + logger.trace("Parsed cookie value [" + cookie.getValue() + "] into locale '" + locale + + "'" + (timeZone != null ? " and time zone '" + timeZone.getID() + "'" : "")); + } + } + if (locale != null) { + exchange.getAttributes().put(LOCALE_REQUEST_ATTRIBUTE_NAME, locale); + } + if (timeZone != null) { + exchange.getAttributes().put(TIME_ZONE_REQUEST_ATTRIBUTE_NAME, timeZone); + } else { + exchange.getAttributes().remove(TIME_ZONE_REQUEST_ATTRIBUTE_NAME); + } + } + } + } +} diff --git a/generators/server/templates/src/main/java/package/repository/UserRepository.java.ejs b/generators/server/templates/src/main/java/package/repository/UserRepository.java.ejs index 8b6c9a258b2..c74c58a7f4d 100644 --- a/generators/server/templates/src/main/java/package/repository/UserRepository.java.ejs +++ b/generators/server/templates/src/main/java/package/repository/UserRepository.java.ejs @@ -472,7 +472,7 @@ public class UserRepository { public static final String USERS_BY_EMAIL_CACHE = "usersByEmail"; <%_ } _%> - <%_ if (!reactive) { _%> + <%_ if (reactive) { _%> private final ReactiveSession session; <%_ } else { _%> private final CqlSession session; @@ -480,7 +480,7 @@ public class UserRepository { private final Validator validator; - <%_ if (!reactive) { _%> + <%_ if (reactive) { _%> private final ReactiveCassandraTemplate cqlTemplate; <%_ } else { _%> private UserDao userDao; diff --git a/generators/server/templates/src/main/java/package/security/DomainUserDetailsService.java.ejs b/generators/server/templates/src/main/java/package/security/DomainUserDetailsService.java.ejs index fc2a8250ccb..8d8637f1b65 100644 --- a/generators/server/templates/src/main/java/package/security/DomainUserDetailsService.java.ejs +++ b/generators/server/templates/src/main/java/package/security/DomainUserDetailsService.java.ejs @@ -62,7 +62,7 @@ public class DomainUserDetailsService implements <% if (reactive) { %>Reactive<% <%_ if (databaseTypeSql) { _%> @Transactional <%_ } _%> - public <% if (!reactive) { %>Mono findByUsername<% } else { %>UserDetails loadUserByUsername<% } %>(final String login) { + public <% if (reactive) { %>Mono findByUsername<% } else { %>UserDetails loadUserByUsername<% } %>(final String login) { log.debug("Authenticating {}", login); if (new EmailValidator().isValid(login, null)) { diff --git a/generators/server/templates/src/main/java/package/service/UserService.java.ejs b/generators/server/templates/src/main/java/package/service/UserService.java.ejs index 95b0f32d821..bd84a3b5722 100644 --- a/generators/server/templates/src/main/java/package/service/UserService.java.ejs +++ b/generators/server/templates/src/main/java/package/service/UserService.java.ejs @@ -847,8 +847,10 @@ public class UserService { this.clearUserCaches(user); <%_ } _%> }); + <%_ } _%> } + <%_ if (reactive) { _%> <%_ if (databaseTypeSql) { _%> @Transactional <%_ } _%> @@ -863,8 +865,8 @@ public class UserService { .doOnNext(this::clearUserCaches) <%_ } _%> .doOnNext(user -> log.debug("Deleted User: {}", user)); - <%_ } _%> } + <%_ } _%> <%_ } _%> <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) { _%> diff --git a/generators/server/templates/src/main/java/package/web/rest/AccountResource.java.ejs b/generators/server/templates/src/main/java/package/web/rest/AccountResource.java.ejs index aba32c28930..32460aad65b 100644 --- a/generators/server/templates/src/main/java/package/web/rest/AccountResource.java.ejs +++ b/generators/server/templates/src/main/java/package/web/rest/AccountResource.java.ejs @@ -523,16 +523,16 @@ public class AccountResource { throw new InvalidPasswordException(); } <%_ if (reactive) { _%> + return userService.completePasswordReset(keyAndPassword.getNewPassword(), keyAndPassword.getKey()) + .switchIfEmpty(Mono.error(new AccountResourceException("No user was found for this reset key"))) + .then(); + <%_ } else { _%> Optional<<%= asEntity('User') %>> user = userService.completePasswordReset(keyAndPassword.getNewPassword(), keyAndPassword.getKey()); if (!user.isPresent()) { throw new AccountResourceException("No user was found for this reset key"); } - <%_ } else { _%> - return userService.completePasswordReset(keyAndPassword.getNewPassword(), keyAndPassword.getKey()) - .switchIfEmpty(Mono.error(new AccountResourceException("No user was found for this reset key"))) - .then(); <%_ } _%> } diff --git a/generators/server/templates/src/main/java/package/web/rest/LogoutResource.java.ejs b/generators/server/templates/src/main/java/package/web/rest/LogoutResource.java.ejs index fb34c2919a5..fee6d4b331f 100644 --- a/generators/server/templates/src/main/java/package/web/rest/LogoutResource.java.ejs +++ b/generators/server/templates/src/main/java/package/web/rest/LogoutResource.java.ejs @@ -21,18 +21,12 @@ package <%= packageName %>.web.rest; import org.springframework.http.ResponseEntity; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.oauth2.client.registration.ClientRegistration; -import org.springframework.security.oauth2.client.registration.<% if (reactive) { %>Reactive<% } %>ClientRegistrationRepository; +import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; import org.springframework.security.oauth2.core.oidc.OidcIdToken; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; -<%_ if (reactive) { _%> -import org.springframework.web.server.WebSession; -import org.springframework.http.server.reactive.ServerHttpRequest; -import reactor.core.publisher.Mono; -<%_ } else { _%> import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpHeaders; -<%_ } _%> import java.util.Map; /** @@ -40,57 +34,20 @@ import java.util.Map; */ @RestController public class LogoutResource { - private final <% if (reactive) { %>Mono<<% } %>ClientRegistration<% if (reactive) { %>><% } %> registration; + private final ClientRegistration registration; - public LogoutResource(<% if (reactive) { %>Reactive<% } %>ClientRegistrationRepository registrations) { + public LogoutResource(ClientRegistrationRepository registrations) { this.registration = registrations.findByRegistrationId("oidc"); } /** * {@code POST /api/logout} : logout the current user. * -<%_ if (!reactive) { _%> * @param request the {@link HttpServletRequest}. -<%_ } _%> * @param idToken the ID token. -<%_ if (reactive) { _%> - * @param request a {@link ServerHttpRequest} request. - * @param session the current {@link WebSession}. -<%_ } _%> * @return the {@link ResponseEntity} with status {@code 200 (OK)} and a body with a global logout URL. */ @PostMapping("/api/logout") -<%_ if (reactive) { _%> - public Mono> logout(@AuthenticationPrincipal(expression = "idToken") OidcIdToken idToken, ServerHttpRequest request, WebSession session) { - return session - .invalidate() - .then( - this.registration.map(oidc -> prepareLogoutUri(request, oidc, idToken)) - ); - } - - private Map prepareLogoutUri(ServerHttpRequest request, ClientRegistration clientRegistration, OidcIdToken idToken) { - StringBuilder logoutUrl = new StringBuilder(); - String issuerUri = clientRegistration.getProviderDetails().getIssuerUri(); - if (issuerUri.contains("auth0.com")) { - logoutUrl.append(issuerUri.endsWith("/") ? issuerUri + "v2/logout" : issuerUri + "/v2/logout"); - } else { - logoutUrl.append(clientRegistration.getProviderDetails().getConfigurationMetadata().get("end_session_endpoint").toString()); - } - - String originUrl = request.getHeaders().getOrigin(); - if (logoutUrl.indexOf("/protocol") > -1) { - logoutUrl.append("?redirect_uri=").append(originUrl); - } else if (logoutUrl.indexOf("auth0.com") > -1) { - // Auth0 - logoutUrl.append("?client_id=").append(clientRegistration.getClientId()).append("&returnTo=").append(originUrl); - } else { - // Okta - logoutUrl.append("?id_token_hint=").append(idToken.getTokenValue()).append("&post_logout_redirect_uri=").append(originUrl); - } - return Map.of("logoutUrl", logoutUrl.toString()); - } -<%_ } else { _%> public ResponseEntity logout(HttpServletRequest request, @AuthenticationPrincipal(expression = "idToken") OidcIdToken idToken) { StringBuilder logoutUrl = new StringBuilder(); @@ -117,6 +74,5 @@ public class LogoutResource { request.getSession().invalidate(); return ResponseEntity.ok().body(Map.of("logoutUrl", logoutUrl.toString())); } -<%_ } _%> } diff --git a/generators/server/templates/src/main/java/package/web/rest/LogoutResource_reactive.java.ejs b/generators/server/templates/src/main/java/package/web/rest/LogoutResource_reactive.java.ejs new file mode 100644 index 00000000000..ae27c52b64e --- /dev/null +++ b/generators/server/templates/src/main/java/package/web/rest/LogoutResource_reactive.java.ejs @@ -0,0 +1,82 @@ +<%# + Copyright 2013-2021 the original author or authors from the JHipster project. + + This file is part of the JHipster project, see https://www.jhipster.tech/ + for more information. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +-%> +package <%= packageName %>.web.rest; + +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository; +import org.springframework.security.oauth2.core.oidc.OidcIdToken; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.WebSession; +import org.springframework.http.server.reactive.ServerHttpRequest; +import reactor.core.publisher.Mono; +import java.util.Map; + +/** + * REST controller for managing global OIDC logout. + */ +@RestController +public class LogoutResource { + private final Mono registration; + + public LogoutResource(ReactiveClientRegistrationRepository registrations) { + this.registration = registrations.findByRegistrationId("oidc"); + } + + /** + * {@code POST /api/logout} : logout the current user. + * + * @param idToken the ID token. + * @param request a {@link ServerHttpRequest} request. + * @param session the current {@link WebSession}. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and a body with a global logout URL. + */ + @PostMapping("/api/logout") + public Mono> logout(@AuthenticationPrincipal(expression = "idToken") OidcIdToken idToken, ServerHttpRequest request, WebSession session) { + return session + .invalidate() + .then( + this.registration.map(oidc -> prepareLogoutUri(request, oidc, idToken)) + ); + } + + private Map prepareLogoutUri(ServerHttpRequest request, ClientRegistration clientRegistration, OidcIdToken idToken) { + StringBuilder logoutUrl = new StringBuilder(); + String issuerUri = clientRegistration.getProviderDetails().getIssuerUri(); + if (issuerUri.contains("auth0.com")) { + logoutUrl.append(issuerUri.endsWith("/") ? issuerUri + "v2/logout" : issuerUri + "/v2/logout"); + } else { + logoutUrl.append(clientRegistration.getProviderDetails().getConfigurationMetadata().get("end_session_endpoint").toString()); + } + + String originUrl = request.getHeaders().getOrigin(); + if (logoutUrl.indexOf("/protocol") > -1) { + logoutUrl.append("?redirect_uri=").append(originUrl); + } else if (logoutUrl.indexOf("auth0.com") > -1) { + // Auth0 + logoutUrl.append("?client_id=").append(clientRegistration.getClientId()).append("&returnTo=").append(originUrl); + } else { + // Okta + logoutUrl.append("?id_token_hint=").append(idToken.getTokenValue()).append("&post_logout_redirect_uri=").append(originUrl); + } + return Map.of("logoutUrl", logoutUrl.toString()); + } +} diff --git a/generators/server/templates/src/main/java/package/web/rest/UserJWTController.java.ejs b/generators/server/templates/src/main/java/package/web/rest/UserJWTController.java.ejs index 33c2412d974..fa58d5e43f7 100644 --- a/generators/server/templates/src/main/java/package/web/rest/UserJWTController.java.ejs +++ b/generators/server/templates/src/main/java/package/web/rest/UserJWTController.java.ejs @@ -51,8 +51,8 @@ import javax.validation.Valid; @RequestMapping("/api") public class UserJWTController { -<%_ if (reactive) { _%> private final TokenProvider tokenProvider; +<%_ if (reactive) { _%> private final ReactiveAuthenticationManager authenticationManager; @@ -75,7 +75,6 @@ public class UserJWTController { }); } <%_ } else { _%> - private final TokenProvider tokenProvider; private final AuthenticationManagerBuilder authenticationManagerBuilder; diff --git a/generators/server/templates/src/test/java/package/security/SecurityUtilsUnitTest.java.ejs b/generators/server/templates/src/test/java/package/security/SecurityUtilsUnitTest.java.ejs index b999f155cfd..b75b715debf 100644 --- a/generators/server/templates/src/test/java/package/security/SecurityUtilsUnitTest.java.ejs +++ b/generators/server/templates/src/test/java/package/security/SecurityUtilsUnitTest.java.ejs @@ -24,18 +24,13 @@ import org.junit.jupiter.api.Test; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; -<%_ if (reactive) { _%> -import org.springframework.security.core.context.ReactiveSecurityContextHolder; -import reactor.util.context.Context; -<%_ } else { _%> import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; - <%_ if (authenticationTypeOauth2) { _%> +<%_ if (authenticationTypeOauth2) { _%> import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; import org.springframework.security.oauth2.core.oidc.OidcIdToken; import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser; import org.springframework.security.oauth2.core.oidc.user.OidcUser; - <%_ } _%> <%_ } _%> <%_ if (authenticationTypeOauth2) { _%> @@ -44,9 +39,7 @@ import java.util.*; <%_ } else { _%> import java.util.ArrayList; import java.util.Collection; - <%_ if (!reactive) { _%> import java.util.Optional; - <%_ } _%> <%_ } _%> import static org.assertj.core.api.Assertions.assertThat; @@ -59,113 +52,6 @@ import static org.springframework.security.oauth2.core.oidc.endpoint.OidcParamet */ class SecurityUtilsUnitTest { -<%_ if (reactive) { _%> - @Test - void testgetCurrentUserLogin() { - String login = SecurityUtils.getCurrentUserLogin() - .contextWrite( - ReactiveSecurityContextHolder.withAuthentication( - new UsernamePasswordAuthenticationToken("admin", "admin") - ) - ) - .block(); - assertThat(login).isEqualTo("admin"); - } - <%_ if (authenticationTypeJwt) { _%> - - @Test - void testgetCurrentUserJWT() { - String jwt = SecurityUtils.getCurrentUserJWT() - .contextWrite( - ReactiveSecurityContextHolder.withAuthentication( - new UsernamePasswordAuthenticationToken("admin", "token") - ) - ) - .block(); - assertThat(jwt).isEqualTo("token"); - } - <%_ } _%> - - @Test - void testIsAuthenticated() { - Boolean isAuthenticated = SecurityUtils.isAuthenticated() - .contextWrite( - ReactiveSecurityContextHolder.withAuthentication( - new UsernamePasswordAuthenticationToken("admin", "admin") - ) - ) - .block(); - assertThat(isAuthenticated).isTrue(); - } - - @Test - void testAnonymousIsNotAuthenticated() { - Collection authorities = new ArrayList<>(); - authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS)); - Boolean isAuthenticated = SecurityUtils.isAuthenticated() - .contextWrite( - ReactiveSecurityContextHolder.withAuthentication( - new UsernamePasswordAuthenticationToken("admin", "admin", authorities) - ) - ) - .block(); - assertThat(isAuthenticated).isFalse(); - } - - @Test - void testHasCurrentUserAnyOfAuthorities() { - Collection authorities = new ArrayList<>(); - authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER)); - Context context = ReactiveSecurityContextHolder.withAuthentication( - new UsernamePasswordAuthenticationToken("admin", "admin", authorities) - ); - Boolean hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserAnyOfAuthorities(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN) - .contextWrite(context) - .block(); - assertThat(hasCurrentUserThisAuthority).isTrue(); - - hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserAnyOfAuthorities(AuthoritiesConstants.ANONYMOUS, AuthoritiesConstants.ADMIN) - .contextWrite(context) - .block(); - assertThat(hasCurrentUserThisAuthority).isFalse(); - } - - @Test - void testHasCurrentUserNoneOfAuthorities() { - Collection authorities = new ArrayList<>(); - authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER)); - Context context = ReactiveSecurityContextHolder.withAuthentication( - new UsernamePasswordAuthenticationToken("admin", "admin", authorities) - ); - Boolean hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserNoneOfAuthorities(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN) - .contextWrite(context) - .block(); - assertThat(hasCurrentUserThisAuthority).isFalse(); - - hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserNoneOfAuthorities(AuthoritiesConstants.ANONYMOUS, AuthoritiesConstants.ADMIN) - .contextWrite(context) - .block(); - assertThat(hasCurrentUserThisAuthority).isTrue(); - } - - @Test - void testHasCurrentUserThisAuthority() { - Collection authorities = new ArrayList<>(); - authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER)); - Context context = ReactiveSecurityContextHolder.withAuthentication( - new UsernamePasswordAuthenticationToken("admin", "admin", authorities) - ); - Boolean hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.USER) - .contextWrite(context) - .block(); - assertThat(hasCurrentUserThisAuthority).isTrue(); - - hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.ADMIN) - .contextWrite(context) - .block(); - assertThat(hasCurrentUserThisAuthority).isFalse(); - } -<%_ } else { /% Not reactive %/_%> @BeforeEach @AfterEach void cleanup() { @@ -180,7 +66,7 @@ class SecurityUtilsUnitTest { Optional login = SecurityUtils.getCurrentUserLogin(); assertThat(login).contains("admin"); } - <%_ if (authenticationTypeOauth2) { _%> +<%_ if (authenticationTypeOauth2) { _%> @Test void testGetCurrentUserLoginForOAuth2() { @@ -229,8 +115,8 @@ class SecurityUtilsUnitTest { .containsAll(expectedAuthorities); } - <%_ } _%> - <%_ if (authenticationTypeJwt) { _%> +<%_ } _%> +<%_ if (authenticationTypeJwt) { _%> @Test void testGetCurrentUserJWT() { @@ -240,7 +126,7 @@ class SecurityUtilsUnitTest { Optional jwt = SecurityUtils.getCurrentUserJWT(); assertThat(jwt).contains("token"); } - <%_ } _%> +<%_ } _%> @Test void testIsAuthenticated() { @@ -297,6 +183,4 @@ class SecurityUtilsUnitTest { assertThat(SecurityUtils.hasCurrentUserNoneOfAuthorities(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN)).isFalse(); assertThat(SecurityUtils.hasCurrentUserNoneOfAuthorities(AuthoritiesConstants.ANONYMOUS, AuthoritiesConstants.ADMIN)).isTrue(); } -<%_ } _%> - } diff --git a/generators/server/templates/src/test/java/package/security/SecurityUtilsUnitTest_reactive.java.ejs b/generators/server/templates/src/test/java/package/security/SecurityUtilsUnitTest_reactive.java.ejs new file mode 100644 index 00000000000..a1faca04b2d --- /dev/null +++ b/generators/server/templates/src/test/java/package/security/SecurityUtilsUnitTest_reactive.java.ejs @@ -0,0 +1,153 @@ +<%# + Copyright 2013-2021 the original author or authors from the JHipster project. + + This file is part of the JHipster project, see https://www.jhipster.tech/ + for more information. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +-%> +package <%= packageName %>.security; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.context.ReactiveSecurityContextHolder; +import reactor.util.context.Context; + +<%_ if (authenticationTypeOauth2) { _%> +import java.time.Instant; +import java.util.*; +<%_ } else { _%> +import java.util.ArrayList; +import java.util.Collection; +<%_ } _%> + +import static org.assertj.core.api.Assertions.assertThat; +<%_ if (authenticationTypeOauth2) { _%> +import static org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames.ID_TOKEN; +<%_ } _%> + +/** + * Test class for the {@link SecurityUtils} utility class. + */ +class SecurityUtilsUnitTest { + + @Test + void testgetCurrentUserLogin() { + String login = SecurityUtils.getCurrentUserLogin() + .contextWrite( + ReactiveSecurityContextHolder.withAuthentication( + new UsernamePasswordAuthenticationToken("admin", "admin") + ) + ) + .block(); + assertThat(login).isEqualTo("admin"); + } + <%_ if (authenticationTypeJwt) { _%> + + @Test + void testgetCurrentUserJWT() { + String jwt = SecurityUtils.getCurrentUserJWT() + .contextWrite( + ReactiveSecurityContextHolder.withAuthentication( + new UsernamePasswordAuthenticationToken("admin", "token") + ) + ) + .block(); + assertThat(jwt).isEqualTo("token"); + } + <%_ } _%> + + @Test + void testIsAuthenticated() { + Boolean isAuthenticated = SecurityUtils.isAuthenticated() + .contextWrite( + ReactiveSecurityContextHolder.withAuthentication( + new UsernamePasswordAuthenticationToken("admin", "admin") + ) + ) + .block(); + assertThat(isAuthenticated).isTrue(); + } + + @Test + void testAnonymousIsNotAuthenticated() { + Collection authorities = new ArrayList<>(); + authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS)); + Boolean isAuthenticated = SecurityUtils.isAuthenticated() + .contextWrite( + ReactiveSecurityContextHolder.withAuthentication( + new UsernamePasswordAuthenticationToken("admin", "admin", authorities) + ) + ) + .block(); + assertThat(isAuthenticated).isFalse(); + } + + @Test + void testHasCurrentUserAnyOfAuthorities() { + Collection authorities = new ArrayList<>(); + authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER)); + Context context = ReactiveSecurityContextHolder.withAuthentication( + new UsernamePasswordAuthenticationToken("admin", "admin", authorities) + ); + Boolean hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserAnyOfAuthorities(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN) + .contextWrite(context) + .block(); + assertThat(hasCurrentUserThisAuthority).isTrue(); + + hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserAnyOfAuthorities(AuthoritiesConstants.ANONYMOUS, AuthoritiesConstants.ADMIN) + .contextWrite(context) + .block(); + assertThat(hasCurrentUserThisAuthority).isFalse(); + } + + @Test + void testHasCurrentUserNoneOfAuthorities() { + Collection authorities = new ArrayList<>(); + authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER)); + Context context = ReactiveSecurityContextHolder.withAuthentication( + new UsernamePasswordAuthenticationToken("admin", "admin", authorities) + ); + Boolean hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserNoneOfAuthorities(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN) + .contextWrite(context) + .block(); + assertThat(hasCurrentUserThisAuthority).isFalse(); + + hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserNoneOfAuthorities(AuthoritiesConstants.ANONYMOUS, AuthoritiesConstants.ADMIN) + .contextWrite(context) + .block(); + assertThat(hasCurrentUserThisAuthority).isTrue(); + } + + @Test + void testHasCurrentUserThisAuthority() { + Collection authorities = new ArrayList<>(); + authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER)); + Context context = ReactiveSecurityContextHolder.withAuthentication( + new UsernamePasswordAuthenticationToken("admin", "admin", authorities) + ); + Boolean hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.USER) + .contextWrite(context) + .block(); + assertThat(hasCurrentUserThisAuthority).isTrue(); + + hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.ADMIN) + .contextWrite(context) + .block(); + assertThat(hasCurrentUserThisAuthority).isFalse(); + } +} diff --git a/generators/server/templates/src/test/java/package/web/rest/errors/ExceptionTranslatorIT.java.ejs b/generators/server/templates/src/test/java/package/web/rest/errors/ExceptionTranslatorIT.java.ejs index 0c7d60c2b0f..298d8c0a89e 100644 --- a/generators/server/templates/src/test/java/package/web/rest/errors/ExceptionTranslatorIT.java.ejs +++ b/generators/server/templates/src/test/java/package/web/rest/errors/ExceptionTranslatorIT.java.ejs @@ -26,141 +26,7 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.security.test.context.support.WithMockUser; -<%_ if (reactive) { _%> - <%_ if (testsNeedCsrf) { _%> -import org.junit.jupiter.api.BeforeEach; - - <%_ } _%> -import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.test.web.reactive.server.WebTestClient; - <%_ if (testsNeedCsrf) { _%> - -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf; - <%_ } _%> - -/** - * Integration tests {@link ExceptionTranslator} controller advice. - */ -@WithMockUser -@AutoConfigureWebTestClient(timeout = IntegrationTest.DEFAULT_TIMEOUT) -@IntegrationTest -class ExceptionTranslatorIT <% if (databaseTypeCassandra) { %>extends AbstractCassandraTest <% } %>{ - - @Autowired - private WebTestClient webTestClient; - <%_ if (testsNeedCsrf) { _%> - - @BeforeEach - public void setupCsrf() { - webTestClient = webTestClient.mutateWith(csrf()); - } - <%_ } _%> - <%_ if (!databaseTypeNo && !databaseTypeCassandra) { _%> - - @Test - void testConcurrencyFailure() { - webTestClient.get().uri("/api/exception-translator-test/concurrency-failure") - .exchange() - .expectStatus().isEqualTo(HttpStatus.CONFLICT) - .expectHeader().contentType(MediaType.APPLICATION_PROBLEM_JSON) - .expectBody() - .jsonPath("$.message").isEqualTo(ErrorConstants.ERR_CONCURRENCY_FAILURE); - } - <%_ } _%> - - @Test - void testMethodArgumentNotValid() { - webTestClient.post().uri("/api/exception-translator-test/method-argument") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue("{}") - .exchange() - .expectHeader().contentType(MediaType.APPLICATION_PROBLEM_JSON) - .expectBody() - .jsonPath("$.message").isEqualTo(ErrorConstants.ERR_VALIDATION) - .jsonPath("$.fieldErrors.[0].objectName").isEqualTo("test") - .jsonPath("$.fieldErrors.[0].field").isEqualTo("test") - .jsonPath("$.fieldErrors.[0].message").isEqualTo("must not be null"); - } - - @Test - void testMissingRequestPart() { - webTestClient.get().uri("/api/exception-translator-test/missing-servlet-request-part") - .exchange() - .expectStatus().isBadRequest() - .expectHeader().contentType(MediaType.APPLICATION_PROBLEM_JSON) - .expectBody() - .jsonPath("$.message").isEqualTo("error.http.400"); - } - - @Test - void testMissingRequestParameter() { - webTestClient.get().uri("/api/exception-translator-test/missing-servlet-request-parameter") - .exchange() - .expectStatus().isBadRequest() - .expectHeader().contentType(MediaType.APPLICATION_PROBLEM_JSON) - .expectBody() - .jsonPath("$.message").isEqualTo("error.http.400"); - } - - @Test - void testAccessDenied() { - webTestClient.get().uri("/api/exception-translator-test/access-denied") - .exchange() - .expectStatus().isForbidden() - .expectHeader().contentType(MediaType.APPLICATION_PROBLEM_JSON) - .expectBody() - .jsonPath("$.message").isEqualTo("error.http.403") - .jsonPath("$.detail").isEqualTo("test access denied!"); - } - - @Test - void testUnauthorized() { - webTestClient.get().uri("/api/exception-translator-test/unauthorized") - .exchange() - .expectStatus().isUnauthorized() - .expectHeader().contentType(MediaType.APPLICATION_PROBLEM_JSON) - .expectBody() - .jsonPath("$.message").isEqualTo("error.http.401") - .jsonPath("$.path").isEqualTo("/api/exception-translator-test/unauthorized") - .jsonPath("$.detail").isEqualTo("test authentication failed!"); - } - @Test - void testMethodNotSupported() { - webTestClient.post().uri("/api/exception-translator-test/access-denied") - .exchange() - .expectStatus().isEqualTo(HttpStatus.METHOD_NOT_ALLOWED) - .expectHeader().contentType(MediaType.APPLICATION_PROBLEM_JSON) - .expectBody() - .jsonPath("$.message").isEqualTo("error.http.405") - .jsonPath("$.detail").isEqualTo("405 METHOD_NOT_ALLOWED \"Request method 'POST' not supported\""); - } - - @Test - void testExceptionWithResponseStatus() { - webTestClient.get().uri("/api/exception-translator-test/response-status") - .exchange() - .expectStatus().isBadRequest() - .expectHeader().contentType(MediaType.APPLICATION_PROBLEM_JSON) - .expectBody() - .jsonPath("$.message").isEqualTo("error.http.400") - .jsonPath("$.title").isEqualTo("test response status"); - } - - @Test - void testInternalServerError() { - webTestClient.get().uri("/api/exception-translator-test/internal-server-error") - .exchange() - .expectHeader().contentType(MediaType.APPLICATION_PROBLEM_JSON) - .expectBody() - .jsonPath("$.message").isEqualTo("error.http.500") - .jsonPath("$.title").isEqualTo("Internal Server Error"); - } - -} -<%_ } else { _%> import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; @@ -184,7 +50,7 @@ class ExceptionTranslatorIT <% if (databaseTypeCassandra) { %>extends AbstractCa @Autowired private MockMvc mockMvc; - <%_ if (!databaseTypeNo && !databaseTypeCassandra) { _%> +<%_ if (!databaseTypeNo && !databaseTypeCassandra) { _%> @Test void testConcurrencyFailure() throws Exception { @@ -193,7 +59,7 @@ class ExceptionTranslatorIT <% if (databaseTypeCassandra) { %>extends AbstractCa .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_CONCURRENCY_FAILURE)); } - <%_ } _%> +<%_ } _%> @Test void testMethodArgumentNotValid() throws Exception { @@ -269,4 +135,3 @@ class ExceptionTranslatorIT <% if (databaseTypeCassandra) { %>extends AbstractCa } } -<%_ } _%> diff --git a/generators/server/templates/src/test/java/package/web/rest/errors/ExceptionTranslatorIT_reactive.java.ejs b/generators/server/templates/src/test/java/package/web/rest/errors/ExceptionTranslatorIT_reactive.java.ejs new file mode 100644 index 00000000000..be41bb77295 --- /dev/null +++ b/generators/server/templates/src/test/java/package/web/rest/errors/ExceptionTranslatorIT_reactive.java.ejs @@ -0,0 +1,161 @@ +<%# + Copyright 2013-2021 the original author or authors from the JHipster project. + + This file is part of the JHipster project, see https://www.jhipster.tech/ + for more information. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +-%> +package <%= packageName %>.web.rest.errors; + +<%_ if (databaseTypeCassandra) { _%> +import <%= packageName %>.AbstractCassandraTest; +<%_ } _%> +import <%= packageName %>.IntegrationTest; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.test.context.support.WithMockUser; +<%_ if (testsNeedCsrf) { _%> +import org.junit.jupiter.api.BeforeEach; + +<%_ } _%> +import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.web.reactive.server.WebTestClient; +<%_ if (testsNeedCsrf) { _%> + +import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf; +<%_ } _%> + +/** + * Integration tests {@link ExceptionTranslator} controller advice. + */ +@WithMockUser +@AutoConfigureWebTestClient(timeout = IntegrationTest.DEFAULT_TIMEOUT) +@IntegrationTest +class ExceptionTranslatorIT <% if (databaseTypeCassandra) { %>extends AbstractCassandraTest <% } %>{ + + @Autowired + private WebTestClient webTestClient; +<%_ if (testsNeedCsrf) { _%> + + @BeforeEach + public void setupCsrf() { + webTestClient = webTestClient.mutateWith(csrf()); + } +<%_ } _%> +<%_ if (!databaseTypeNo && !databaseTypeCassandra) { _%> + + @Test + void testConcurrencyFailure() { + webTestClient.get().uri("/api/exception-translator-test/concurrency-failure") + .exchange() + .expectStatus().isEqualTo(HttpStatus.CONFLICT) + .expectHeader().contentType(MediaType.APPLICATION_PROBLEM_JSON) + .expectBody() + .jsonPath("$.message").isEqualTo(ErrorConstants.ERR_CONCURRENCY_FAILURE); + } +<%_ } _%> + + @Test + void testMethodArgumentNotValid() { + webTestClient.post().uri("/api/exception-translator-test/method-argument") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue("{}") + .exchange() + .expectHeader().contentType(MediaType.APPLICATION_PROBLEM_JSON) + .expectBody() + .jsonPath("$.message").isEqualTo(ErrorConstants.ERR_VALIDATION) + .jsonPath("$.fieldErrors.[0].objectName").isEqualTo("test") + .jsonPath("$.fieldErrors.[0].field").isEqualTo("test") + .jsonPath("$.fieldErrors.[0].message").isEqualTo("must not be null"); + } + + @Test + void testMissingRequestPart() { + webTestClient.get().uri("/api/exception-translator-test/missing-servlet-request-part") + .exchange() + .expectStatus().isBadRequest() + .expectHeader().contentType(MediaType.APPLICATION_PROBLEM_JSON) + .expectBody() + .jsonPath("$.message").isEqualTo("error.http.400"); + } + + @Test + void testMissingRequestParameter() { + webTestClient.get().uri("/api/exception-translator-test/missing-servlet-request-parameter") + .exchange() + .expectStatus().isBadRequest() + .expectHeader().contentType(MediaType.APPLICATION_PROBLEM_JSON) + .expectBody() + .jsonPath("$.message").isEqualTo("error.http.400"); + } + + @Test + void testAccessDenied() { + webTestClient.get().uri("/api/exception-translator-test/access-denied") + .exchange() + .expectStatus().isForbidden() + .expectHeader().contentType(MediaType.APPLICATION_PROBLEM_JSON) + .expectBody() + .jsonPath("$.message").isEqualTo("error.http.403") + .jsonPath("$.detail").isEqualTo("test access denied!"); + } + + @Test + void testUnauthorized() { + webTestClient.get().uri("/api/exception-translator-test/unauthorized") + .exchange() + .expectStatus().isUnauthorized() + .expectHeader().contentType(MediaType.APPLICATION_PROBLEM_JSON) + .expectBody() + .jsonPath("$.message").isEqualTo("error.http.401") + .jsonPath("$.path").isEqualTo("/api/exception-translator-test/unauthorized") + .jsonPath("$.detail").isEqualTo("test authentication failed!"); + } + + @Test + void testMethodNotSupported() { + webTestClient.post().uri("/api/exception-translator-test/access-denied") + .exchange() + .expectStatus().isEqualTo(HttpStatus.METHOD_NOT_ALLOWED) + .expectHeader().contentType(MediaType.APPLICATION_PROBLEM_JSON) + .expectBody() + .jsonPath("$.message").isEqualTo("error.http.405") + .jsonPath("$.detail").isEqualTo("405 METHOD_NOT_ALLOWED \"Request method 'POST' not supported\""); + } + + @Test + void testExceptionWithResponseStatus() { + webTestClient.get().uri("/api/exception-translator-test/response-status") + .exchange() + .expectStatus().isBadRequest() + .expectHeader().contentType(MediaType.APPLICATION_PROBLEM_JSON) + .expectBody() + .jsonPath("$.message").isEqualTo("error.http.400") + .jsonPath("$.title").isEqualTo("test response status"); + } + + @Test + void testInternalServerError() { + webTestClient.get().uri("/api/exception-translator-test/internal-server-error") + .exchange() + .expectHeader().contentType(MediaType.APPLICATION_PROBLEM_JSON) + .expectBody() + .jsonPath("$.message").isEqualTo("error.http.500") + .jsonPath("$.title").isEqualTo("Internal Server Error"); + } + +} From ff4431e5d756cb61ac5ea0b55dbce23b5c8163ab Mon Sep 17 00:00:00 2001 From: Charlie Mordant Date: Wed, 12 Jan 2022 22:09:50 +0100 Subject: [PATCH 3/5] inversion of reactive and non-reactive conditionals --- .../main/java/package/web/rest/PublicUserResource.java.ejs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/generators/server/templates/src/main/java/package/web/rest/PublicUserResource.java.ejs b/generators/server/templates/src/main/java/package/web/rest/PublicUserResource.java.ejs index e38eebd81aa..4042ae6e68e 100644 --- a/generators/server/templates/src/main/java/package/web/rest/PublicUserResource.java.ejs +++ b/generators/server/templates/src/main/java/package/web/rest/PublicUserResource.java.ejs @@ -194,12 +194,12 @@ public class PublicUserResource { <%_ } _%> <%_ } else { _%> <%_ if (reactive) { _%> + return userRepository.search(User.PREFIX, query).map(<%= asDto('User') %>::new).collectList(); + <%_ } else { _%> return StreamSupport .stream(userRepository.search(User.PREFIX, query).spliterator(), false) .map(<%= asDto('User') %>::new) .collect(Collectors.toList()); - <%_ } else { _%> - return userRepository.search(User.PREFIX, query).map(<%= asDto('User') %>::new).collectList(); <%_ } _%> <%_ } _%> } From fbab2d24136711e4652db93d6c8a8ab029d12155 Mon Sep 17 00:00:00 2001 From: Charlie Mordant Date: Sun, 16 Jan 2022 21:39:51 +0100 Subject: [PATCH 4/5] some code cleansing --- .../src/main/java/package/service/EntityService.java.ejs | 2 +- .../java/package/service/impl/EntityServiceImpl.java.ejs | 2 +- .../main/java/package/web/rest/EntityResource.java.ejs | 4 ++-- .../test/java/package/web/rest/EntityResourceIT.java.ejs | 5 ++--- .../src/test/java/package/IntegrationTest.java.ejs | 8 ++++---- package-lock.json | 1 - 6 files changed, 10 insertions(+), 12 deletions(-) diff --git a/generators/entity-server/templates/src/main/java/package/service/EntityService.java.ejs b/generators/entity-server/templates/src/main/java/package/service/EntityService.java.ejs index 9c9bd46ebd8..649f38f975a 100644 --- a/generators/entity-server/templates/src/main/java/package/service/EntityService.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/service/EntityService.java.ejs @@ -79,7 +79,7 @@ public interface <%= entityClass %>Service { * @param pageable the pagination information.<% } %> * @return the list of entities. */ - <% if (paginationNo) { %><%= listOrFlux %><<%= instanceType %><% } else { %><%= pageOrFlux %><<%= instanceType %><% } %>> findAll(<% if (!paginationNo) { %>Pageable pageable<% } %>); + <% if (paginationNo) { %><%= listOrFlux %><% } else { %><%= pageOrFlux %><% } %><<%= instanceType %>> findAll(<% if (!paginationNo) { %>Pageable pageable<% } %>); <%_ for (const relationship of relationships) { _%> <%_ if (relationship.relationshipOneToOne && !relationship.ownerSide) { _%> /** diff --git a/generators/entity-server/templates/src/main/java/package/service/impl/EntityServiceImpl.java.ejs b/generators/entity-server/templates/src/main/java/package/service/impl/EntityServiceImpl.java.ejs index 6787ef12159..21faa8c4c47 100644 --- a/generators/entity-server/templates/src/main/java/package/service/impl/EntityServiceImpl.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/service/impl/EntityServiceImpl.java.ejs @@ -147,7 +147,7 @@ public class <%= serviceClassName %><% if (serviceImpl) { %> implements <%= enti <%_ if (databaseTypeSql) { _%> @Transactional(readOnly = true) <%_ } _%> - public <% if (paginationNo) { %><%= listOrFlux %><<%= instanceType %><% } else { %><%= pageOrFlux %><<%= instanceType %><% } %>> findAll(<% if (!paginationNo) { %>Pageable pageable<% } %>) { + public <% if (paginationNo) { %><%= listOrFlux %><% } else { %><%= pageOrFlux %><% } %><<%= instanceType %>> findAll(<% if (!paginationNo) { %>Pageable pageable<% } %>) { log.debug("Request to get all <%= entityClassPlural %>"); <%_ if (paginationNo) { _%> return <%= entityInstance %>Repository.<% if (relationshipsContainEagerLoad) { %>findAllWithEagerRelationships<% } else { %>findAll<% } %>()<% if (dtoMapstruct) { %><% if (!reactive) { %>.stream()<% } %> diff --git a/generators/entity-server/templates/src/main/java/package/web/rest/EntityResource.java.ejs b/generators/entity-server/templates/src/main/java/package/web/rest/EntityResource.java.ejs index f0f62b9ed8b..d7dab3f784d 100644 --- a/generators/entity-server/templates/src/main/java/package/web/rest/EntityResource.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/web/rest/EntityResource.java.ejs @@ -257,13 +257,13 @@ public class <%= entityClass %>Resource { <%_ if (reactive) { _%> .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND))) .map(result -> ResponseEntity.ok() - .headers(HeaderUtil.createEntityUpdateAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, result.get<%= primaryKey.nameCapitalized %>()<% if (primaryKey.type !== 'String') { %>.toString()<% } %>)) + .headers(HeaderUtil.createEntityUpdateAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, result.get<%= primaryKey.nameCapitalized %>()<% if (!primaryKey.typeString) { %>.toString()<% } %>)) .body(result) ); }); <%_ } else { _%> return ResponseEntity.ok() - .headers(HeaderUtil.createEntityUpdateAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, <%= instanceName %>.get<%= primaryKey.nameCapitalized %>()<% if (primaryKey.type !== 'String') { %>.toString()<% } %>)) + .headers(HeaderUtil.createEntityUpdateAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, <%= instanceName %>.get<%= primaryKey.nameCapitalized %>()<% if (!primaryKey.typeString) { %>.toString()<% } %>)) .body(result); <%_ } _%> } diff --git a/generators/entity-server/templates/src/test/java/package/web/rest/EntityResourceIT.java.ejs b/generators/entity-server/templates/src/test/java/package/web/rest/EntityResourceIT.java.ejs index 4b39cea3028..0d2a18d7a7f 100644 --- a/generators/entity-server/templates/src/test/java/package/web/rest/EntityResourceIT.java.ejs +++ b/generators/entity-server/templates/src/test/java/package/web/rest/EntityResourceIT.java.ejs @@ -463,11 +463,10 @@ if (field.fieldTypeString || field.blobContentTypeText) { private EntityManager em; <%_ } _%> -<%_ if (reactive) { _%> @Autowired +<%_ if (reactive) { _%> private WebTestClient webTestClient; <%_ } else { _%> - @Autowired private MockMvc rest<%= entityClass %>MockMvc; <%_ } _%> @@ -1370,7 +1369,7 @@ _%> .exchange() .expectStatus().isOk(); <%_ } else { _%> - rest<%= entityClass %>MockMvc.perform(put(ENTITY_API_URL_ID, <%= (dtoMapstruct ? asDto(entityInstance) : 'updated' + persistClass) %>.get<%= primaryKey.nameCapitalized %>())<% if (testsNeedCsrf) { %>.with(csrf())<% }%> + rest<%= entityClass %>MockMvc.perform(put(ENTITY_API_URL_ID, <%= (dtoMapstruct ? asDto(entityInstance) : 'updated' + persistClass) %>.get<%= primaryKey.nameCapitalized %>())<% if (testsNeedCsrf) { %>.with(csrf())<% } %> .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(<%= (dtoMapstruct ? asDto(entityInstance) : 'updated' + persistClass) %>))) .andExpect(status().isOk()); diff --git a/generators/server/templates/src/test/java/package/IntegrationTest.java.ejs b/generators/server/templates/src/test/java/package/IntegrationTest.java.ejs index a001aeb2143..eaa4103def3 100644 --- a/generators/server/templates/src/test/java/package/IntegrationTest.java.ejs +++ b/generators/server/templates/src/test/java/package/IntegrationTest.java.ejs @@ -77,11 +77,11 @@ public @interface IntegrationTest { <%_ if (reactive) { _%> // 5s is the spring default https://github.com/spring-projects/spring-framework/blob/29185a3d28fa5e9c1b4821ffe519ef6f56b51962/spring-test/src/main/java/org/springframework/test/web/reactive/server/DefaultWebTestClient.java#L106 <%_ if (databaseTypeMongodb && reactive) { _%> - public static final String DEFAULT_TIMEOUT = "PT10S"; - public static final String DEFAULT_ENTITY_TIMEOUT = "PT10S"; + String DEFAULT_TIMEOUT = "PT10S"; + String DEFAULT_ENTITY_TIMEOUT = "PT10S"; <%_ } else { _%> - public static final String DEFAULT_TIMEOUT = "PT5S"; - public static final String DEFAULT_ENTITY_TIMEOUT = "PT5S"; + String DEFAULT_TIMEOUT = "PT5S"; + String DEFAULT_ENTITY_TIMEOUT = "PT5S"; <%_ } _%> <%_ } _%> } diff --git a/package-lock.json b/package-lock.json index 413b249d724..e88fac62d63 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5,7 +5,6 @@ "requires": true, "packages": { "": { - "name": "generator-jhipster", "version": "7.5.0", "license": "Apache-2.0", "dependencies": { From 67f252d3af85ad04bd3eabfc4b41006831dbb0a0 Mon Sep 17 00:00:00 2001 From: Charlie Mordant Date: Wed, 19 Jan 2022 16:00:05 +0100 Subject: [PATCH 5/5] code improvement according to review --- .../main/java/package/web/rest/PublicUserResource.java.ejs | 2 +- .../test/java/package/security/SecurityUtilsUnitTest.java.ejs | 2 -- .../src/test/java/package/web/rest/AccountResourceIT.java.ejs | 4 +++- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/generators/server/templates/src/main/java/package/web/rest/PublicUserResource.java.ejs b/generators/server/templates/src/main/java/package/web/rest/PublicUserResource.java.ejs index 4042ae6e68e..1afd61b14c1 100644 --- a/generators/server/templates/src/main/java/package/web/rest/PublicUserResource.java.ejs +++ b/generators/server/templates/src/main/java/package/web/rest/PublicUserResource.java.ejs @@ -67,7 +67,7 @@ import reactor.core.publisher.Mono; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; <%_ } _%> -<%_ if (!reactive) { _%> +<%_ if (reactive) { _%> import java.util.ArrayList; import java.util.List; import java.util.Arrays; diff --git a/generators/server/templates/src/test/java/package/security/SecurityUtilsUnitTest.java.ejs b/generators/server/templates/src/test/java/package/security/SecurityUtilsUnitTest.java.ejs index b75b715debf..143b6e76cc7 100644 --- a/generators/server/templates/src/test/java/package/security/SecurityUtilsUnitTest.java.ejs +++ b/generators/server/templates/src/test/java/package/security/SecurityUtilsUnitTest.java.ejs @@ -31,9 +31,7 @@ import org.springframework.security.oauth2.client.authentication.OAuth2Authentic import org.springframework.security.oauth2.core.oidc.OidcIdToken; import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser; import org.springframework.security.oauth2.core.oidc.user.OidcUser; -<%_ } _%> -<%_ if (authenticationTypeOauth2) { _%> import java.time.Instant; import java.util.*; <%_ } else { _%> diff --git a/generators/server/templates/src/test/java/package/web/rest/AccountResourceIT.java.ejs b/generators/server/templates/src/test/java/package/web/rest/AccountResourceIT.java.ejs index ac5e9b17b3a..7e290f85b25 100644 --- a/generators/server/templates/src/test/java/package/web/rest/AccountResourceIT.java.ejs +++ b/generators/server/templates/src/test/java/package/web/rest/AccountResourceIT.java.ejs @@ -93,8 +93,10 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.hasItem; <%_ } _%> import static <%= packageName %>.web.rest.AccountResourceIT.TEST_USER_LOGIN; -<%_ if (reactive && testsNeedCsrf) { _%> +<%_ if (reactive) { _%> + <%_ if (testsNeedCsrf) { _%> import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf; + <%_ } _%> <%_ } else { _%> <%_ if (testsNeedCsrf) { _%> import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;