void reindexForClass(
}
})
.filter(Objects::nonNull)
- .collect(Collectors.toList());
+ .toList();
int size = 100;
for (int i = 0; i <= jpaRepository.count() / size; i++) {
diff --git a/src/main/java/org/jhipster/health/service/MailService.java b/src/main/java/org/jhipster/health/service/MailService.java
index e0454fa4..ffe1e8d3 100644
--- a/src/main/java/org/jhipster/health/service/MailService.java
+++ b/src/main/java/org/jhipster/health/service/MailService.java
@@ -1,9 +1,9 @@
package org.jhipster.health.service;
+import jakarta.mail.MessagingException;
+import jakarta.mail.internet.MimeMessage;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
-import javax.mail.MessagingException;
-import javax.mail.internet.MimeMessage;
import org.jhipster.health.domain.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -14,11 +14,11 @@
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
-import org.thymeleaf.spring5.SpringTemplateEngine;
+import org.thymeleaf.spring6.SpringTemplateEngine;
import tech.jhipster.config.JHipsterProperties;
/**
- * Service for sending emails.
+ * Service for sending emails asynchronously.
*
* We use the {@link Async} annotation to send emails asynchronously.
*/
@@ -53,6 +53,10 @@ public MailService(
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
+ this.sendEmailSync(to, subject, content, isMultipart, isHtml);
+ }
+
+ private void sendEmailSync(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
log.debug(
"Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
isMultipart,
@@ -79,6 +83,10 @@ public void sendEmail(String to, String subject, String content, boolean isMulti
@Async
public void sendEmailFromTemplate(User user, String templateName, String titleKey) {
+ this.sendEmailFromTemplateSync(user, templateName, titleKey);
+ }
+
+ private void sendEmailFromTemplateSync(User user, String templateName, String titleKey) {
if (user.getEmail() == null) {
log.debug("Email doesn't exist for user '{}'", user.getLogin());
return;
@@ -89,24 +97,24 @@ public void sendEmailFromTemplate(User user, String templateName, String titleKe
context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl());
String content = templateEngine.process(templateName, context);
String subject = messageSource.getMessage(titleKey, null, locale);
- sendEmail(user.getEmail(), subject, content, false, true);
+ this.sendEmailSync(user.getEmail(), subject, content, false, true);
}
@Async
public void sendActivationEmail(User user) {
log.debug("Sending activation email to '{}'", user.getEmail());
- sendEmailFromTemplate(user, "mail/activationEmail", "email.activation.title");
+ this.sendEmailFromTemplateSync(user, "mail/activationEmail", "email.activation.title");
}
@Async
public void sendCreationEmail(User user) {
log.debug("Sending creation email to '{}'", user.getEmail());
- sendEmailFromTemplate(user, "mail/creationEmail", "email.activation.title");
+ this.sendEmailFromTemplateSync(user, "mail/creationEmail", "email.activation.title");
}
@Async
public void sendPasswordResetMail(User user) {
log.debug("Sending password reset email to '{}'", user.getEmail());
- sendEmailFromTemplate(user, "mail/passwordResetEmail", "email.reset.title");
+ this.sendEmailFromTemplateSync(user, "mail/passwordResetEmail", "email.reset.title");
}
}
diff --git a/src/main/java/org/jhipster/health/service/UserService.java b/src/main/java/org/jhipster/health/service/UserService.java
index 092c505d..28387ed5 100644
--- a/src/main/java/org/jhipster/health/service/UserService.java
+++ b/src/main/java/org/jhipster/health/service/UserService.java
@@ -182,7 +182,7 @@ public User createUser(AdminUserDTO userDTO) {
user.setAuthorities(authorities);
}
userRepository.save(user);
- userSearchRepository.save(user);
+ userSearchRepository.index(user);
this.clearUserCaches(user);
log.debug("Created Information for User: {}", user);
return user;
@@ -195,8 +195,7 @@ public User createUser(AdminUserDTO userDTO) {
* @return updated user.
*/
public Optional updateUser(AdminUserDTO userDTO) {
- return Optional
- .of(userRepository.findById(userDTO.getId()))
+ return Optional.of(userRepository.findById(userDTO.getId()))
.filter(Optional::isPresent)
.map(Optional::get)
.map(user -> {
@@ -219,7 +218,8 @@ public Optional updateUser(AdminUserDTO userDTO) {
.filter(Optional::isPresent)
.map(Optional::get)
.forEach(managedAuthorities::add);
- userSearchRepository.save(user);
+ userRepository.save(user);
+ userSearchRepository.index(user);
this.clearUserCaches(user);
log.debug("Changed Information for User: {}", user);
return user;
@@ -232,7 +232,7 @@ public void deleteUser(String login) {
.findOneByLogin(login)
.ifPresent(user -> {
userRepository.delete(user);
- userSearchRepository.delete(user);
+ userSearchRepository.deleteFromIndex(user);
this.clearUserCaches(user);
log.debug("Deleted User: {}", user);
});
@@ -248,8 +248,7 @@ public void deleteUser(String login) {
* @param imageUrl image URL of user.
*/
public void updateUser(String firstName, String lastName, String email, String langKey, String imageUrl) {
- SecurityUtils
- .getCurrentUserLogin()
+ SecurityUtils.getCurrentUserLogin()
.flatMap(userRepository::findOneByLogin)
.ifPresent(user -> {
user.setFirstName(firstName);
@@ -259,7 +258,8 @@ public void updateUser(String firstName, String lastName, String email, String l
}
user.setLangKey(langKey);
user.setImageUrl(imageUrl);
- userSearchRepository.save(user);
+ userRepository.save(user);
+ userSearchRepository.index(user);
this.clearUserCaches(user);
log.debug("Changed Information for User: {}", user);
});
@@ -267,8 +267,7 @@ public void updateUser(String firstName, String lastName, String email, String l
@Transactional
public void changePassword(String currentClearTextPassword, String newPassword) {
- SecurityUtils
- .getCurrentUserLogin()
+ SecurityUtils.getCurrentUserLogin()
.flatMap(userRepository::findOneByLogin)
.ifPresent(user -> {
String currentEncryptedPassword = user.getPassword();
@@ -314,7 +313,7 @@ public void removeNotActivatedUsers() {
.forEach(user -> {
log.debug("Deleting not activated user {}", user.getLogin());
userRepository.delete(user);
- userSearchRepository.delete(user);
+ userSearchRepository.deleteFromIndex(user);
this.clearUserCaches(user);
});
}
@@ -325,7 +324,7 @@ public void removeNotActivatedUsers() {
*/
@Transactional(readOnly = true)
public List getAuthorities() {
- return authorityRepository.findAll().stream().map(Authority::getName).collect(Collectors.toList());
+ return authorityRepository.findAll().stream().map(Authority::getName).toList();
}
private void clearUserCaches(User user) {
diff --git a/src/main/java/org/jhipster/health/service/dto/AdminUserDTO.java b/src/main/java/org/jhipster/health/service/dto/AdminUserDTO.java
index b457662e..00ee170f 100644
--- a/src/main/java/org/jhipster/health/service/dto/AdminUserDTO.java
+++ b/src/main/java/org/jhipster/health/service/dto/AdminUserDTO.java
@@ -1,10 +1,10 @@
package org.jhipster.health.service.dto;
+import jakarta.validation.constraints.*;
import java.io.Serializable;
import java.time.Instant;
import java.util.Set;
import java.util.stream.Collectors;
-import javax.validation.constraints.*;
import org.jhipster.health.config.Constants;
import org.jhipster.health.domain.Authority;
import org.jhipster.health.domain.User;
diff --git a/src/main/java/org/jhipster/health/service/dto/package-info.java b/src/main/java/org/jhipster/health/service/dto/package-info.java
index 5f15b131..c7380ce5 100644
--- a/src/main/java/org/jhipster/health/service/dto/package-info.java
+++ b/src/main/java/org/jhipster/health/service/dto/package-info.java
@@ -1,4 +1,4 @@
/**
- * Data Transfer Objects.
+ * Data transfer objects for rest mapping.
*/
package org.jhipster.health.service.dto;
diff --git a/src/main/java/org/jhipster/health/service/mapper/UserMapper.java b/src/main/java/org/jhipster/health/service/mapper/UserMapper.java
index a8a63030..0a8c46ae 100644
--- a/src/main/java/org/jhipster/health/service/mapper/UserMapper.java
+++ b/src/main/java/org/jhipster/health/service/mapper/UserMapper.java
@@ -21,7 +21,7 @@
public class UserMapper {
public List usersToUserDTOs(List users) {
- return users.stream().filter(Objects::nonNull).map(this::userToUserDTO).collect(Collectors.toList());
+ return users.stream().filter(Objects::nonNull).map(this::userToUserDTO).toList();
}
public UserDTO userToUserDTO(User user) {
@@ -29,7 +29,7 @@ public UserDTO userToUserDTO(User user) {
}
public List usersToAdminUserDTOs(List users) {
- return users.stream().filter(Objects::nonNull).map(this::userToAdminUserDTO).collect(Collectors.toList());
+ return users.stream().filter(Objects::nonNull).map(this::userToAdminUserDTO).toList();
}
public AdminUserDTO userToAdminUserDTO(User user) {
@@ -37,7 +37,7 @@ public AdminUserDTO userToAdminUserDTO(User user) {
}
public List userDTOsToUsers(List userDTOs) {
- return userDTOs.stream().filter(Objects::nonNull).map(this::userDTOToUser).collect(Collectors.toList());
+ return userDTOs.stream().filter(Objects::nonNull).map(this::userDTOToUser).toList();
}
public User userDTOToUser(AdminUserDTO userDTO) {
@@ -63,15 +63,14 @@ private Set authoritiesFromStrings(Set authoritiesAsString) {
Set authorities = new HashSet<>();
if (authoritiesAsString != null) {
- authorities =
- authoritiesAsString
- .stream()
- .map(string -> {
- Authority auth = new Authority();
- auth.setName(string);
- return auth;
- })
- .collect(Collectors.toSet());
+ authorities = authoritiesAsString
+ .stream()
+ .map(string -> {
+ Authority auth = new Authority();
+ auth.setName(string);
+ return auth;
+ })
+ .collect(Collectors.toSet());
}
return authorities;
diff --git a/src/main/java/org/jhipster/health/service/mapper/package-info.java b/src/main/java/org/jhipster/health/service/mapper/package-info.java
index b971ff47..c06969c8 100644
--- a/src/main/java/org/jhipster/health/service/mapper/package-info.java
+++ b/src/main/java/org/jhipster/health/service/mapper/package-info.java
@@ -1,4 +1,4 @@
/**
- * MapStruct mappers for mapping domain objects and Data Transfer Objects.
+ * Data transfer objects mappers.
*/
package org.jhipster.health.service.mapper;
diff --git a/src/main/java/org/jhipster/health/service/package-info.java b/src/main/java/org/jhipster/health/service/package-info.java
index 8aa1c8a5..37278afc 100644
--- a/src/main/java/org/jhipster/health/service/package-info.java
+++ b/src/main/java/org/jhipster/health/service/package-info.java
@@ -1,4 +1,4 @@
/**
- * Service layer beans.
+ * Service layer.
*/
package org.jhipster.health.service;
diff --git a/src/main/java/org/jhipster/health/web/filter/SpaWebFilter.java b/src/main/java/org/jhipster/health/web/filter/SpaWebFilter.java
new file mode 100644
index 00000000..7b1dd471
--- /dev/null
+++ b/src/main/java/org/jhipster/health/web/filter/SpaWebFilter.java
@@ -0,0 +1,34 @@
+package org.jhipster.health.web.filter;
+
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import org.springframework.web.filter.OncePerRequestFilter;
+
+public class SpaWebFilter extends OncePerRequestFilter {
+
+ /**
+ * Forwards any unmapped paths (except those containing a period) to the client {@code index.html}.
+ */
+ @Override
+ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
+ throws ServletException, IOException {
+ // Request URI includes the contextPath if any, removed it.
+ String path = request.getRequestURI().substring(request.getContextPath().length());
+ if (
+ !path.startsWith("/api") &&
+ !path.startsWith("/management") &&
+ !path.startsWith("/v3/api-docs") &&
+ !path.startsWith("/h2-console") &&
+ !path.contains(".") &&
+ path.matches("/(.*)")
+ ) {
+ request.getRequestDispatcher("/index.html").forward(request, response);
+ return;
+ }
+
+ filterChain.doFilter(request, response);
+ }
+}
diff --git a/src/main/java/org/jhipster/health/web/filter/package-info.java b/src/main/java/org/jhipster/health/web/filter/package-info.java
new file mode 100644
index 00000000..bc73f239
--- /dev/null
+++ b/src/main/java/org/jhipster/health/web/filter/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Request chain filters.
+ */
+package org.jhipster.health.web.filter;
diff --git a/src/main/java/org/jhipster/health/web/rest/AccountResource.java b/src/main/java/org/jhipster/health/web/rest/AccountResource.java
index d50d6eb8..c8ac4b28 100644
--- a/src/main/java/org/jhipster/health/web/rest/AccountResource.java
+++ b/src/main/java/org/jhipster/health/web/rest/AccountResource.java
@@ -1,8 +1,7 @@
package org.jhipster.health.web.rest;
+import jakarta.validation.Valid;
import java.util.*;
-import javax.servlet.http.HttpServletRequest;
-import javax.validation.Valid;
import org.apache.commons.lang3.StringUtils;
import org.jhipster.health.domain.User;
import org.jhipster.health.repository.UserRepository;
@@ -79,18 +78,6 @@ public void activateAccount(@RequestParam(value = "key") String key) {
}
}
- /**
- * {@code GET /authenticate} : check if the user is authenticated, and return its login.
- *
- * @param request the HTTP request.
- * @return the login if the user is authenticated.
- */
- @GetMapping("/authenticate")
- public String isAuthenticated(HttpServletRequest request) {
- log.debug("REST request to check if the current user is authenticated");
- return request.getRemoteUser();
- }
-
/**
* {@code GET /account} : get the current user.
*
@@ -114,11 +101,10 @@ public AdminUserDTO getAccount() {
*/
@PostMapping("/account")
public void saveAccount(@Valid @RequestBody AdminUserDTO userDTO) {
- String userLogin = SecurityUtils
- .getCurrentUserLogin()
+ String userLogin = SecurityUtils.getCurrentUserLogin()
.orElseThrow(() -> new AccountResourceException("Current user login not found"));
Optional existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail());
- if (existingUser.isPresent() && (!existingUser.get().getLogin().equalsIgnoreCase(userLogin))) {
+ if (existingUser.isPresent() && (!existingUser.orElseThrow().getLogin().equalsIgnoreCase(userLogin))) {
throw new EmailAlreadyUsedException();
}
Optional user = userRepository.findOneByLogin(userLogin);
@@ -157,7 +143,7 @@ public void changePassword(@RequestBody PasswordChangeDTO passwordChangeDto) {
public void requestPasswordReset(@RequestBody String mail) {
Optional user = userService.requestPasswordReset(mail);
if (user.isPresent()) {
- mailService.sendPasswordResetMail(user.get());
+ mailService.sendPasswordResetMail(user.orElseThrow());
} else {
// Pretend the request has been successful to prevent checking which emails really exist
// but log that an invalid attempt has been made
diff --git a/src/main/java/org/jhipster/health/web/rest/AuthenticateController.java b/src/main/java/org/jhipster/health/web/rest/AuthenticateController.java
new file mode 100644
index 00000000..5c0458c0
--- /dev/null
+++ b/src/main/java/org/jhipster/health/web/rest/AuthenticateController.java
@@ -0,0 +1,124 @@
+package org.jhipster.health.web.rest;
+
+import static org.jhipster.health.security.SecurityUtils.AUTHORITIES_KEY;
+import static org.jhipster.health.security.SecurityUtils.JWT_ALGORITHM;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.validation.Valid;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.stream.Collectors;
+import org.jhipster.health.web.rest.vm.LoginVM;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.oauth2.jwt.JwsHeader;
+import org.springframework.security.oauth2.jwt.JwtClaimsSet;
+import org.springframework.security.oauth2.jwt.JwtEncoder;
+import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
+import org.springframework.web.bind.annotation.*;
+
+/**
+ * Controller to authenticate users.
+ */
+@RestController
+@RequestMapping("/api")
+public class AuthenticateController {
+
+ private final Logger log = LoggerFactory.getLogger(AuthenticateController.class);
+
+ private final JwtEncoder jwtEncoder;
+
+ @Value("${jhipster.security.authentication.jwt.token-validity-in-seconds:0}")
+ private long tokenValidityInSeconds;
+
+ @Value("${jhipster.security.authentication.jwt.token-validity-in-seconds-for-remember-me:0}")
+ private long tokenValidityInSecondsForRememberMe;
+
+ private final AuthenticationManagerBuilder authenticationManagerBuilder;
+
+ public AuthenticateController(JwtEncoder jwtEncoder, AuthenticationManagerBuilder authenticationManagerBuilder) {
+ this.jwtEncoder = jwtEncoder;
+ 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 = this.createToken(authentication, loginVM.isRememberMe());
+ HttpHeaders httpHeaders = new HttpHeaders();
+ httpHeaders.setBearerAuth(jwt);
+ return new ResponseEntity<>(new JWTToken(jwt), httpHeaders, HttpStatus.OK);
+ }
+
+ /**
+ * {@code GET /authenticate} : check if the user is authenticated, and return its login.
+ *
+ * @param request the HTTP request.
+ * @return the login if the user is authenticated.
+ */
+ @GetMapping("/authenticate")
+ public String isAuthenticated(HttpServletRequest request) {
+ log.debug("REST request to check if the current user is authenticated");
+ return request.getRemoteUser();
+ }
+
+ public String createToken(Authentication authentication, boolean rememberMe) {
+ String authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.joining(" "));
+
+ Instant now = Instant.now();
+ Instant validity;
+ if (rememberMe) {
+ validity = now.plus(this.tokenValidityInSecondsForRememberMe, ChronoUnit.SECONDS);
+ } else {
+ validity = now.plus(this.tokenValidityInSeconds, ChronoUnit.SECONDS);
+ }
+
+ // @formatter:off
+ JwtClaimsSet claims = JwtClaimsSet.builder()
+ .issuedAt(now)
+ .expiresAt(validity)
+ .subject(authentication.getName())
+ .claim(AUTHORITIES_KEY, authorities)
+ .build();
+
+ JwsHeader jwsHeader = JwsHeader.with(JWT_ALGORITHM).build();
+ return this.jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, claims)).getTokenValue();
+ }
+
+ /**
+ * Object to return as body in JWT Authentication.
+ */
+ static class JWTToken {
+
+ private String idToken;
+
+ JWTToken(String idToken) {
+ this.idToken = idToken;
+ }
+
+ @JsonProperty("id_token")
+ String getIdToken() {
+ return idToken;
+ }
+
+ void setIdToken(String idToken) {
+ this.idToken = idToken;
+ }
+ }
+}
diff --git a/src/main/java/org/jhipster/health/web/rest/AuthorityResource.java b/src/main/java/org/jhipster/health/web/rest/AuthorityResource.java
new file mode 100644
index 00000000..95090a57
--- /dev/null
+++ b/src/main/java/org/jhipster/health/web/rest/AuthorityResource.java
@@ -0,0 +1,101 @@
+package org.jhipster.health.web.rest;
+
+import jakarta.validation.Valid;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.List;
+import java.util.Optional;
+import org.jhipster.health.domain.Authority;
+import org.jhipster.health.repository.AuthorityRepository;
+import org.jhipster.health.web.rest.errors.BadRequestAlertException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.web.bind.annotation.*;
+import tech.jhipster.web.util.HeaderUtil;
+import tech.jhipster.web.util.ResponseUtil;
+
+/**
+ * REST controller for managing {@link org.jhipster.health.domain.Authority}.
+ */
+@RestController
+@RequestMapping("/api/authorities")
+@Transactional
+public class AuthorityResource {
+
+ private final Logger log = LoggerFactory.getLogger(AuthorityResource.class);
+
+ private static final String ENTITY_NAME = "adminAuthority";
+
+ @Value("${jhipster.clientApp.name}")
+ private String applicationName;
+
+ private final AuthorityRepository authorityRepository;
+
+ public AuthorityResource(AuthorityRepository authorityRepository) {
+ this.authorityRepository = authorityRepository;
+ }
+
+ /**
+ * {@code POST /authorities} : Create a new authority.
+ *
+ * @param authority the authority to create.
+ * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new authority, or with status {@code 400 (Bad Request)} if the authority has already an ID.
+ * @throws URISyntaxException if the Location URI syntax is incorrect.
+ */
+ @PostMapping("")
+ @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')")
+ public ResponseEntity createAuthority(@Valid @RequestBody Authority authority) throws URISyntaxException {
+ log.debug("REST request to save Authority : {}", authority);
+ if (authorityRepository.existsById(authority.getName())) {
+ throw new BadRequestAlertException("authority already exists", ENTITY_NAME, "idexists");
+ }
+ authority = authorityRepository.save(authority);
+ return ResponseEntity.created(new URI("/api/authorities/" + authority.getName()))
+ .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, authority.getName()))
+ .body(authority);
+ }
+
+ /**
+ * {@code GET /authorities} : get all the authorities.
+ *
+ * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of authorities in body.
+ */
+ @GetMapping("")
+ @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')")
+ public List getAllAuthorities() {
+ log.debug("REST request to get all Authorities");
+ return authorityRepository.findAll();
+ }
+
+ /**
+ * {@code GET /authorities/:id} : get the "id" authority.
+ *
+ * @param id the id of the authority to retrieve.
+ * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the authority, or with status {@code 404 (Not Found)}.
+ */
+ @GetMapping("/{id}")
+ @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')")
+ public ResponseEntity getAuthority(@PathVariable("id") String id) {
+ log.debug("REST request to get Authority : {}", id);
+ Optional authority = authorityRepository.findById(id);
+ return ResponseUtil.wrapOrNotFound(authority);
+ }
+
+ /**
+ * {@code DELETE /authorities/:id} : delete the "id" authority.
+ *
+ * @param id the id of the authority to delete.
+ * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
+ */
+ @DeleteMapping("/{id}")
+ @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')")
+ public ResponseEntity deleteAuthority(@PathVariable("id") String id) {
+ log.debug("REST request to delete Authority : {}", id);
+ authorityRepository.deleteById(id);
+ return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id)).build();
+ }
+}
diff --git a/src/main/java/org/jhipster/health/web/rest/BloodPressureResource.java b/src/main/java/org/jhipster/health/web/rest/BloodPressureResource.java
index 43d28efd..1bf76763 100644
--- a/src/main/java/org/jhipster/health/web/rest/BloodPressureResource.java
+++ b/src/main/java/org/jhipster/health/web/rest/BloodPressureResource.java
@@ -1,8 +1,8 @@
package org.jhipster.health.web.rest;
-import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
-import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery;
-
+import co.elastic.clients.elasticsearch._types.query_dsl.*;
+import jakarta.validation.Valid;
+import jakarta.validation.constraints.NotNull;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.LocalDate;
@@ -13,10 +13,6 @@
import java.util.List;
import java.util.Objects;
import java.util.Optional;
-import javax.validation.Valid;
-import javax.validation.constraints.NotNull;
-import org.elasticsearch.index.query.BoolQueryBuilder;
-import org.elasticsearch.index.query.QueryBuilders;
import org.jhipster.health.domain.BloodPressure;
import org.jhipster.health.repository.BloodPressureRepository;
import org.jhipster.health.repository.UserRepository;
@@ -24,6 +20,7 @@
import org.jhipster.health.security.AuthoritiesConstants;
import org.jhipster.health.security.SecurityUtils;
import org.jhipster.health.web.rest.errors.BadRequestAlertException;
+import org.jhipster.health.web.rest.errors.ElasticsearchExceptionMapper;
import org.jhipster.health.web.rest.vm.BloodPressureByPeriod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -45,7 +42,7 @@
* REST controller for managing {@link org.jhipster.health.domain.BloodPressure}.
*/
@RestController
-@RequestMapping("/api")
+@RequestMapping("/api/blood-pressures")
@Transactional
public class BloodPressureResource {
@@ -79,7 +76,7 @@ public BloodPressureResource(
* @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new bloodPressure, or with status {@code 400 (Bad Request)} if the bloodPressure has already an ID.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
- @PostMapping("/blood-pressures")
+ @PostMapping("")
public ResponseEntity createBloodPressure(@Valid @RequestBody BloodPressure bloodPressure) throws URISyntaxException {
log.debug("REST request to save BloodPressure : {}", bloodPressure);
if (bloodPressure.getId() != null) {
@@ -89,25 +86,24 @@ public ResponseEntity createBloodPressure(@Valid @RequestBody Blo
log.debug("No user passed in, using current user: {}", SecurityUtils.getCurrentUserLogin().orElse(""));
bloodPressure.setUser(userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin().orElse("")).orElse(null));
}
- BloodPressure result = bloodPressureRepository.save(bloodPressure);
- bloodPressureSearchRepository.index(result);
- return ResponseEntity
- .created(new URI("/api/blood-pressures/" + result.getId()))
- .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
- .body(result);
+ bloodPressure = bloodPressureRepository.save(bloodPressure);
+ bloodPressureSearchRepository.index(bloodPressure);
+ return ResponseEntity.created(new URI("/api/blood-pressures/" + bloodPressure.getId()))
+ .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, bloodPressure.getId().toString()))
+ .body(bloodPressure);
}
/**
* {@code PUT /blood-pressures/:id} : Updates an existing bloodPressure.
*
- * @param id the id of the bloodPressure to save.
+ * @param id the id of the bloodPressure to save.
* @param bloodPressure the bloodPressure to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated bloodPressure,
* or with status {@code 400 (Bad Request)} if the bloodPressure is not valid,
* or with status {@code 500 (Internal Server Error)} if the bloodPressure couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
- @PutMapping("/blood-pressures/{id}")
+ @PutMapping("/{id}")
public ResponseEntity> updateBloodPressure(
@PathVariable(value = "id", required = false) final Long id,
@Valid @RequestBody BloodPressure bloodPressure
@@ -130,18 +126,17 @@ public ResponseEntity> updateBloodPressure(
return new ResponseEntity<>("error.http.403", HttpStatus.FORBIDDEN);
}
- BloodPressure result = bloodPressureRepository.save(bloodPressure);
- bloodPressureSearchRepository.index(result);
- return ResponseEntity
- .ok()
+ bloodPressure = bloodPressureRepository.save(bloodPressure);
+ bloodPressureSearchRepository.index(bloodPressure);
+ return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, bloodPressure.getId().toString()))
- .body(result);
+ .body(bloodPressure);
}
/**
* {@code PATCH /blood-pressures/:id} : Partial updates given fields of an existing bloodPressure, field will ignore if it is null
*
- * @param id the id of the bloodPressure to save.
+ * @param id the id of the bloodPressure to save.
* @param bloodPressure the bloodPressure to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated bloodPressure,
* or with status {@code 400 (Bad Request)} if the bloodPressure is not valid,
@@ -149,7 +144,7 @@ public ResponseEntity> updateBloodPressure(
* or with status {@code 500 (Internal Server Error)} if the bloodPressure couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
- @PatchMapping(value = "/blood-pressures/{id}", consumes = { "application/json", "application/merge-patch+json" })
+ @PatchMapping(value = "/{id}", consumes = { "application/json", "application/merge-patch+json" })
public ResponseEntity> partialUpdateBloodPressure(
@PathVariable(value = "id", required = false) final Long id,
@NotNull @RequestBody BloodPressure bloodPressure
@@ -189,8 +184,7 @@ public ResponseEntity> partialUpdateBloodPressure(
})
.map(bloodPressureRepository::save)
.map(savedBloodPressure -> {
- bloodPressureSearchRepository.save(savedBloodPressure);
-
+ bloodPressureSearchRepository.index(savedBloodPressure);
return savedBloodPressure;
});
@@ -203,19 +197,23 @@ public ResponseEntity> partialUpdateBloodPressure(
/**
* {@code GET /blood-pressures} : get all the bloodPressures.
*
- * @param pageable the pagination information.
+ * @param pageable the pagination information.
* @param eagerload flag to eager load entities from relationships (This is applicable for many-to-many).
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of bloodPressures in body.
*/
- @GetMapping("/blood-pressures")
+ @GetMapping("")
public ResponseEntity> getAllBloodPressures(
- @org.springdoc.api.annotations.ParameterObject Pageable pageable,
- @RequestParam(required = false, defaultValue = "false") boolean eagerload
+ @org.springdoc.core.annotations.ParameterObject Pageable pageable,
+ @RequestParam(name = "eagerload", required = false, defaultValue = "true") boolean eagerload
) {
log.debug("REST request to get a page of BloodPressures");
Page page;
if (SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.ADMIN)) {
- page = bloodPressureRepository.findAllByOrderByTimestampDesc(pageable);
+ if (eagerload) {
+ page = bloodPressureRepository.findAllWithEagerRelationships(pageable);
+ } else {
+ page = bloodPressureRepository.findAll(pageable);
+ }
} else {
page = bloodPressureRepository.findByUserIsCurrentUser(pageable);
}
@@ -229,8 +227,8 @@ public ResponseEntity> getAllBloodPressures(
* @param id the id of the bloodPressure to retrieve.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the bloodPressure, or with status {@code 404 (Not Found)}.
*/
- @GetMapping("/blood-pressures/{id}")
- public ResponseEntity> getBloodPressure(@PathVariable Long id) {
+ @GetMapping("/{id}")
+ public ResponseEntity> getBloodPressure(@PathVariable("id") Long id) {
log.debug("REST request to get BloodPressure : {}", id);
Optional bloodPressure = bloodPressureRepository.findOneWithEagerRelationships(id);
if (
@@ -250,8 +248,8 @@ public ResponseEntity> getBloodPressure(@PathVariable Long id) {
* @param id the id of the bloodPressure to delete.
* @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
*/
- @DeleteMapping("/blood-pressures/{id}")
- public ResponseEntity> deleteBloodPressure(@PathVariable Long id) {
+ @DeleteMapping("/{id}")
+ public ResponseEntity> deleteBloodPressure(@PathVariable("id") Long id) {
log.debug("REST request to delete BloodPressure : {}", id);
Optional bloodPressure = bloodPressureRepository.findById(id);
if (
@@ -263,43 +261,51 @@ public ResponseEntity> deleteBloodPressure(@PathVariable Long id) {
return new ResponseEntity<>("error.http.403", HttpStatus.FORBIDDEN);
}
bloodPressureRepository.deleteById(id);
- bloodPressureSearchRepository.deleteById(id);
- return ResponseEntity
- .noContent()
+ bloodPressureSearchRepository.deleteFromIndexById(id);
+ return ResponseEntity.noContent()
.headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString()))
.build();
}
/**
- * {@code SEARCH /_search/blood-pressures?query=:query} : search for the bloodPressure corresponding
+ * {@code SEARCH /blood-pressures/_search?query=:query} : search for the bloodPressure corresponding
* to the query.
*
- * @param query the query of the bloodPressure search.
+ * @param query the query of the bloodPressure search.
* @param pageable the pagination information.
* @return the result of the search.
*/
- @GetMapping("/_search/blood-pressures")
+ @GetMapping("/_search")
public ResponseEntity> searchBloodPressures(
- @RequestParam String query,
- @org.springdoc.api.annotations.ParameterObject Pageable pageable
+ @RequestParam("query") String query,
+ @org.springdoc.core.annotations.ParameterObject Pageable pageable
) {
log.debug("REST request to search for a page of BloodPressures for query {}", query);
- BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery().must(queryStringQuery(query));
if (SecurityUtils.isAuthenticated() && !SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.ADMIN)) {
- queryBuilder = queryBuilder.filter(matchQuery("user.login", SecurityUtils.getCurrentUserLogin().orElse("")));
+ QueryVariant filterByUser = new MatchQuery.Builder()
+ .field("user.login")
+ .query(SecurityUtils.getCurrentUserLogin().orElse(""))
+ .build();
+ BoolQuery.Builder boolQueryBuilder = QueryBuilders.bool();
+ boolQueryBuilder.should(new Query(filterByUser));
+ query = new Query(boolQueryBuilder.build()).toString();
+ }
+ try {
+ Page page = bloodPressureSearchRepository.search(query, pageable);
+ HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
+ return ResponseEntity.ok().headers(headers).body(page.getContent());
+ } catch (RuntimeException e) {
+ throw ElasticsearchExceptionMapper.mapException(e);
}
- Page page = bloodPressureSearchRepository.search(queryBuilder, pageable);
- HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
- return ResponseEntity.ok().headers(headers).body(page.getContent());
}
/**
- * {@code GET /bp-by-days/:days} : get all the blood pressure readings by last x days.
+ * {@code GET blood-pressures/by-days/:days} : get all the blood pressure readings by last x days.
*
* @param days the number of days.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the {@link BloodPressureByPeriod}.
*/
- @RequestMapping(value = "/bp-by-days/{days}")
+ @RequestMapping(value = "/by-days/{days}")
public ResponseEntity getByDays(@PathVariable int days) {
ZonedDateTime rightNow = ZonedDateTime.now();
ZonedDateTime daysAgo = rightNow.minusDays(days);
@@ -314,12 +320,12 @@ public ResponseEntity getByDays(@PathVariable int days) {
}
/**
- * {@code GET /bp-by-month/:date} : get all the blood pressure readings by last x days.
+ * {@code GET /blood-pressures/by-month/:date} : get all the blood pressure readings by last x days.
*
* @param date the year and month in yyyy-MM format.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the {@link BloodPressureByPeriod}.
*/
- @GetMapping("/bp-by-month/{date}")
+ @GetMapping("/by-month/{date}")
public ResponseEntity getByMonth(@PathVariable @DateTimeFormat(pattern = "yyyy-MM") YearMonth date) {
LocalDate firstDay = date.atDay(1);
LocalDate lastDay = date.atEndOfMonth();
diff --git a/src/main/java/org/jhipster/health/web/rest/ClientForwardController.java b/src/main/java/org/jhipster/health/web/rest/ClientForwardController.java
deleted file mode 100644
index 02c5b825..00000000
--- a/src/main/java/org/jhipster/health/web/rest/ClientForwardController.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package org.jhipster.health.web.rest;
-
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.GetMapping;
-
-@Controller
-public class ClientForwardController {
-
- /**
- * Forwards any unmapped paths (except those containing a period) to the client {@code index.html}.
- * @return forward to client {@code index.html}.
- */
- @GetMapping(value = "/**/{path:[^\\.]*}")
- public String forward() {
- return "forward:/";
- }
-}
diff --git a/src/main/java/org/jhipster/health/web/rest/ElasticsearchIndexResource.java b/src/main/java/org/jhipster/health/web/rest/ElasticsearchIndexResource.java
index 49f90cb2..dd2ab541 100644
--- a/src/main/java/org/jhipster/health/web/rest/ElasticsearchIndexResource.java
+++ b/src/main/java/org/jhipster/health/web/rest/ElasticsearchIndexResource.java
@@ -56,8 +56,7 @@ public ResponseEntity reindexAll() throws URISyntaxException {
public ResponseEntity reindexSelected(@RequestBody List selectedEntities) throws URISyntaxException {
log.info("REST request to reindex Elasticsearch by user : {}, entities: {}", SecurityUtils.getCurrentUserLogin(), selectedEntities);
elasticsearchIndexService.reindexSelected(selectedEntities, false);
- return ResponseEntity
- .accepted()
+ return ResponseEntity.accepted()
.headers(HeaderUtil.createAlert(applicationName, "elasticsearch.reindex.acceptedSelected", ""))
.build();
}
diff --git a/src/main/java/org/jhipster/health/web/rest/PointsResource.java b/src/main/java/org/jhipster/health/web/rest/PointsResource.java
index b8f37172..46fc72aa 100644
--- a/src/main/java/org/jhipster/health/web/rest/PointsResource.java
+++ b/src/main/java/org/jhipster/health/web/rest/PointsResource.java
@@ -1,8 +1,8 @@
package org.jhipster.health.web.rest;
-import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
-import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery;
-
+import co.elastic.clients.elasticsearch._types.query_dsl.*;
+import jakarta.validation.Valid;
+import jakarta.validation.constraints.NotNull;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.DayOfWeek;
@@ -12,10 +12,6 @@
import java.util.List;
import java.util.Objects;
import java.util.Optional;
-import javax.validation.Valid;
-import javax.validation.constraints.NotNull;
-import org.elasticsearch.index.query.BoolQueryBuilder;
-import org.elasticsearch.index.query.QueryBuilders;
import org.jhipster.health.domain.Points;
import org.jhipster.health.repository.PointsRepository;
import org.jhipster.health.repository.UserRepository;
@@ -23,6 +19,7 @@
import org.jhipster.health.security.AuthoritiesConstants;
import org.jhipster.health.security.SecurityUtils;
import org.jhipster.health.web.rest.errors.BadRequestAlertException;
+import org.jhipster.health.web.rest.errors.ElasticsearchExceptionMapper;
import org.jhipster.health.web.rest.vm.PointsPerMonth;
import org.jhipster.health.web.rest.vm.PointsPerWeek;
import org.slf4j.Logger;
@@ -45,7 +42,7 @@
* REST controller for managing {@link org.jhipster.health.domain.Points}.
*/
@RestController
-@RequestMapping("/api")
+@RequestMapping("/api/points")
@Transactional
public class PointsResource {
@@ -75,7 +72,7 @@ public PointsResource(PointsRepository pointsRepository, PointsSearchRepository
* @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new points, or with status {@code 400 (Bad Request)} if the points has already an ID.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
- @PostMapping("/points")
+ @PostMapping("")
public ResponseEntity createPoints(@Valid @RequestBody Points points) throws URISyntaxException {
log.debug("REST request to save Points : {}", points);
if (points.getId() != null) {
@@ -85,12 +82,11 @@ public ResponseEntity createPoints(@Valid @RequestBody Points points) th
log.debug("No user passed in, using current user: {}", SecurityUtils.getCurrentUserLogin().orElse(""));
points.setUser(userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin().orElse("")).orElse(null));
}
- Points result = pointsRepository.save(points);
- pointsSearchRepository.index(result);
- return ResponseEntity
- .created(new URI("/api/points/" + result.getId()))
- .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
- .body(result);
+ points = pointsRepository.save(points);
+ pointsSearchRepository.index(points);
+ return ResponseEntity.created(new URI("/api/points/" + points.getId()))
+ .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, points.getId().toString()))
+ .body(points);
}
/**
@@ -103,7 +99,7 @@ public ResponseEntity createPoints(@Valid @RequestBody Points points) th
* or with status {@code 500 (Internal Server Error)} if the points couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
- @PutMapping("/points/{id}")
+ @PutMapping("/{id}")
public ResponseEntity> updatePoints(@PathVariable(value = "id", required = false) final Long id, @Valid @RequestBody Points points)
throws URISyntaxException {
log.debug("REST request to update Points : {}, {}", id, points);
@@ -124,12 +120,11 @@ public ResponseEntity> updatePoints(@PathVariable(value = "id", required = fal
return new ResponseEntity<>("error.http.403", HttpStatus.FORBIDDEN);
}
- Points result = pointsRepository.save(points);
- pointsSearchRepository.index(result);
- return ResponseEntity
- .ok()
+ points = pointsRepository.save(points);
+ pointsSearchRepository.index(points);
+ return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, points.getId().toString()))
- .body(result);
+ .body(points);
}
/**
@@ -143,7 +138,7 @@ public ResponseEntity> updatePoints(@PathVariable(value = "id", required = fal
* or with status {@code 500 (Internal Server Error)} if the points couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
- @PatchMapping(value = "/points/{id}", consumes = { "application/json", "application/merge-patch+json" })
+ @PatchMapping(value = "/{id}", consumes = { "application/json", "application/merge-patch+json" })
public ResponseEntity> partialUpdatePoints(
@PathVariable(value = "id", required = false) final Long id,
@NotNull @RequestBody Points points
@@ -189,8 +184,7 @@ public ResponseEntity> partialUpdatePoints(
})
.map(pointsRepository::save)
.map(savedPoints -> {
- pointsSearchRepository.save(savedPoints);
-
+ pointsSearchRepository.index(savedPoints);
return savedPoints;
});
@@ -207,15 +201,19 @@ public ResponseEntity> partialUpdatePoints(
* @param eagerload flag to eager load entities from relationships (This is applicable for many-to-many).
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of points in body.
*/
- @GetMapping("/points")
+ @GetMapping("")
public ResponseEntity> getAllPoints(
- @org.springdoc.api.annotations.ParameterObject Pageable pageable,
- @RequestParam(required = false, defaultValue = "false") boolean eagerload
+ @org.springdoc.core.annotations.ParameterObject Pageable pageable,
+ @RequestParam(name = "eagerload", required = false, defaultValue = "true") boolean eagerload
) {
log.debug("REST request to get a page of Points");
Page page;
if (SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.ADMIN)) {
- page = pointsRepository.findAllByOrderByDateDesc(pageable);
+ if (eagerload) {
+ page = pointsRepository.findAllWithEagerRelationships(pageable);
+ } else {
+ page = pointsRepository.findAll(pageable);
+ }
} else {
page = pointsRepository.findByUserIsCurrentUser(pageable);
}
@@ -229,8 +227,8 @@ public ResponseEntity> getAllPoints(
* @param id the id of the points to retrieve.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the points, or with status {@code 404 (Not Found)}.
*/
- @GetMapping("/points/{id}")
- public ResponseEntity> getPoints(@PathVariable Long id) {
+ @GetMapping("/{id}")
+ public ResponseEntity> getPoints(@PathVariable("id") Long id) {
log.debug("REST request to get Points : {}", id);
Optional points = pointsRepository.findOneWithEagerRelationships(id);
if (
@@ -250,8 +248,8 @@ public ResponseEntity> getPoints(@PathVariable Long id) {
* @param id the id of the points to delete.
* @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
*/
- @DeleteMapping("/points/{id}")
- public ResponseEntity> deletePoints(@PathVariable Long id) {
+ @DeleteMapping("/{id}")
+ public ResponseEntity> deletePoints(@PathVariable("id") Long id) {
log.debug("REST request to delete Points : {}", id);
Optional points = pointsRepository.findById(id);
if (
@@ -263,42 +261,50 @@ public ResponseEntity> deletePoints(@PathVariable Long id) {
return new ResponseEntity<>("error.http.403", HttpStatus.FORBIDDEN);
}
pointsRepository.deleteById(id);
- pointsSearchRepository.deleteById(id);
- return ResponseEntity
- .noContent()
+ pointsSearchRepository.deleteFromIndexById(id);
+ return ResponseEntity.noContent()
.headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString()))
.build();
}
/**
- * {@code SEARCH /_search/points?query=:query} : search for the points corresponding
+ * {@code SEARCH /points/_search?query=:query} : search for the points corresponding
* to the query.
*
* @param query the query of the points search.
* @param pageable the pagination information.
* @return the result of the search.
*/
- @GetMapping("/_search/points")
+ @GetMapping("/_search")
public ResponseEntity> searchPoints(
- @RequestParam String query,
- @org.springdoc.api.annotations.ParameterObject Pageable pageable
+ @RequestParam("query") String query,
+ @org.springdoc.core.annotations.ParameterObject Pageable pageable
) {
log.debug("REST request to search for a page of Points for query {}", query);
- BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery().must(queryStringQuery(query));
if (SecurityUtils.isAuthenticated() && !SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.ADMIN)) {
- queryBuilder = queryBuilder.filter(matchQuery("user.login", SecurityUtils.getCurrentUserLogin().orElse("")));
+ QueryVariant filterByUser = new MatchQuery.Builder()
+ .field("user.login")
+ .query(SecurityUtils.getCurrentUserLogin().orElse(""))
+ .build();
+ BoolQuery.Builder boolQueryBuilder = QueryBuilders.bool();
+ boolQueryBuilder.should(new Query(filterByUser));
+ query = new Query(boolQueryBuilder.build()).toString();
+ }
+ try {
+ Page page = pointsSearchRepository.search(query, pageable);
+ HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
+ return ResponseEntity.ok().headers(headers).body(page.getContent());
+ } catch (RuntimeException e) {
+ throw ElasticsearchExceptionMapper.mapException(e);
}
- Page page = pointsSearchRepository.search(queryBuilder, pageable);
- HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
- return ResponseEntity.ok().headers(headers).body(page.getContent());
}
/**
- * {@code GET /points-by-week/yyyy-MM-dd} : get all the points for a particular week.
+ * {@code GET /points/by-week/yyyy-MM-dd} : get all the points for a particular week.
*
* @param date a date in a week to find points for.
*/
- @GetMapping("/points-by-week/{date}")
+ @GetMapping("/by-week/{date}")
public ResponseEntity getPointsByWeek(@PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
// Get first and last days of week
LocalDate startOfWeek = date.with(DayOfWeek.MONDAY);
@@ -312,11 +318,11 @@ public ResponseEntity getPointsByWeek(@PathVariable @DateTimeForm
}
/**
- * {@code GET /points-by-month} : get all the points for a particular current month.
+ * {@code GET /points/by-month} : get all the points for a particular current month.
*
* @param yearWithMonth the year and month to find points for.
*/
- @GetMapping("/points-by-month/{yearWithMonth}")
+ @GetMapping("/by-month/{yearWithMonth}")
public ResponseEntity getPointsByMonth(@PathVariable @DateTimeFormat(pattern = "yyyy-MM") YearMonth yearWithMonth) {
// Get last day of the month
LocalDate endOfMonth = yearWithMonth.atEndOfMonth();
@@ -330,12 +336,12 @@ public ResponseEntity getPointsByMonth(@PathVariable @DateTimeFo
}
/**
- * {@code GET /points-this-week} : get all the points for the current week
+ * {@code GET /points/this-week} : get all the points for the current week
*
* @param timezone the user's timezone
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and a count of points in body.
*/
- @GetMapping("/points-this-week")
+ @GetMapping("/this-week")
public ResponseEntity getPointsThisWeek(@RequestParam(value = "tz", required = false) String timezone) {
// Get current date (with timezone if passed in)
LocalDate now = LocalDate.now();
diff --git a/src/main/java/org/jhipster/health/web/rest/PreferencesResource.java b/src/main/java/org/jhipster/health/web/rest/PreferencesResource.java
index 42c03106..e0ee844b 100644
--- a/src/main/java/org/jhipster/health/web/rest/PreferencesResource.java
+++ b/src/main/java/org/jhipster/health/web/rest/PreferencesResource.java
@@ -1,20 +1,18 @@
package org.jhipster.health.web.rest;
-import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
-import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery;
+import static org.springframework.data.elasticsearch.client.elc.Queries.matchQuery;
+import static org.springframework.data.elasticsearch.client.elc.Queries.queryStringQuery;
+import co.elastic.clients.elasticsearch._types.query_dsl.*;
+import jakarta.validation.Valid;
+import jakarta.validation.constraints.NotNull;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
-import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
-import javax.validation.Valid;
-import javax.validation.constraints.NotNull;
-import org.elasticsearch.index.query.BoolQueryBuilder;
-import org.elasticsearch.index.query.QueryBuilders;
import org.jhipster.health.domain.Preferences;
import org.jhipster.health.repository.PreferencesRepository;
import org.jhipster.health.repository.UserRepository;
@@ -22,6 +20,7 @@
import org.jhipster.health.security.AuthoritiesConstants;
import org.jhipster.health.security.SecurityUtils;
import org.jhipster.health.web.rest.errors.BadRequestAlertException;
+import org.jhipster.health.web.rest.errors.ElasticsearchExceptionMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
@@ -36,7 +35,7 @@
* REST controller for managing {@link org.jhipster.health.domain.Preferences}.
*/
@RestController
-@RequestMapping("/api")
+@RequestMapping("/api/preferences")
@Transactional
public class PreferencesResource {
@@ -70,7 +69,7 @@ public PreferencesResource(
* @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new preferences, or with status {@code 400 (Bad Request)} if the preferences has already an ID.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
- @PostMapping("/preferences")
+ @PostMapping("")
public ResponseEntity createPreferences(@Valid @RequestBody Preferences preferences) throws URISyntaxException {
log.debug("REST request to save Preferences : {}", preferences);
if (preferences.getId() != null) {
@@ -80,13 +79,11 @@ public ResponseEntity createPreferences(@Valid @RequestBody Prefere
log.debug("No user passed in, setting preferences for current user: {}", SecurityUtils.getCurrentUserLogin().orElse(""));
preferences.setUser(userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin().orElse("")).orElse(null));
}
-
- Preferences result = preferencesRepository.save(preferences);
- preferencesSearchRepository.index(result);
- return ResponseEntity
- .created(new URI("/api/preferences/" + result.getId()))
- .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
- .body(result);
+ preferences = preferencesRepository.save(preferences);
+ preferencesSearchRepository.index(preferences);
+ return ResponseEntity.created(new URI("/api/preferences/" + preferences.getId()))
+ .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, preferences.getId().toString()))
+ .body(preferences);
}
/**
@@ -99,7 +96,7 @@ public ResponseEntity createPreferences(@Valid @RequestBody Prefere
* or with status {@code 500 (Internal Server Error)} if the preferences couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
- @PutMapping("/preferences/{id}")
+ @PutMapping("/{id}")
public ResponseEntity> updatePreferences(
@PathVariable(value = "id", required = false) final Long id,
@Valid @RequestBody Preferences preferences
@@ -122,12 +119,11 @@ public ResponseEntity> updatePreferences(
return new ResponseEntity<>("error.http.403", HttpStatus.FORBIDDEN);
}
- Preferences result = preferencesRepository.save(preferences);
- preferencesSearchRepository.index(result);
- return ResponseEntity
- .ok()
+ preferences = preferencesRepository.save(preferences);
+ preferencesSearchRepository.index(preferences);
+ return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, preferences.getId().toString()))
- .body(result);
+ .body(preferences);
}
/**
@@ -141,7 +137,7 @@ public ResponseEntity> updatePreferences(
* or with status {@code 500 (Internal Server Error)} if the preferences couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
- @PatchMapping(value = "/preferences/{id}", consumes = { "application/json", "application/merge-patch+json" })
+ @PatchMapping(value = "/{id}", consumes = { "application/json", "application/merge-patch+json" })
public ResponseEntity> partialUpdatePreferences(
@PathVariable(value = "id", required = false) final Long id,
@NotNull @RequestBody Preferences preferences
@@ -178,8 +174,7 @@ public ResponseEntity> partialUpdatePreferences(
})
.map(preferencesRepository::save)
.map(savedPreferences -> {
- preferencesSearchRepository.save(savedPreferences);
-
+ preferencesSearchRepository.index(savedPreferences);
return savedPreferences;
});
@@ -195,12 +190,18 @@ public ResponseEntity> partialUpdatePreferences(
* @param eagerload flag to eager load entities from relationships (This is applicable for many-to-many).
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of preferences in body.
*/
- @GetMapping("/preferences")
- public List getAllPreferences(@RequestParam(required = false, defaultValue = "false") boolean eagerload) {
+ @GetMapping("")
+ public List getAllPreferences(
+ @RequestParam(name = "eagerload", required = false, defaultValue = "true") boolean eagerload
+ ) {
log.debug("REST request to get all Preferences");
List preferences = new ArrayList<>();
if (SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.ADMIN)) {
- preferences = preferencesRepository.findAll();
+ if (eagerload) {
+ preferences = preferencesRepository.findAllWithEagerRelationships();
+ } else {
+ preferences = preferencesRepository.findAll();
+ }
} else {
Preferences userPreferences = getUserPreferences().getBody();
// don't return default value of 10 points in this method
@@ -217,8 +218,8 @@ public List getAllPreferences(@RequestParam(required = false, defau
* @param id the id of the preferences to retrieve.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the preferences, or with status {@code 404 (Not Found)}.
*/
- @GetMapping("/preferences/{id}")
- public ResponseEntity> getPreferences(@PathVariable Long id) {
+ @GetMapping("/{id}")
+ public ResponseEntity> getPreferences(@PathVariable("id") Long id) {
log.debug("REST request to get Preferences : {}", id);
Optional preferences = preferencesRepository.findOneWithEagerRelationships(id);
if (
@@ -238,8 +239,8 @@ public ResponseEntity> getPreferences(@PathVariable Long id) {
* @param id the id of the preferences to delete.
* @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
*/
- @DeleteMapping("/preferences/{id}")
- public ResponseEntity> deletePreferences(@PathVariable Long id) {
+ @DeleteMapping("/{id}")
+ public ResponseEntity> deletePreferences(@PathVariable("id") Long id) {
log.debug("REST request to delete Preferences : {}", id);
Optional preferences = preferencesRepository.findById(id);
if (
@@ -251,36 +252,44 @@ public ResponseEntity> deletePreferences(@PathVariable Long id) {
return new ResponseEntity<>("error.http.403", HttpStatus.FORBIDDEN);
}
preferencesRepository.deleteById(id);
- preferencesSearchRepository.deleteById(id);
- return ResponseEntity
- .noContent()
+ preferencesSearchRepository.deleteFromIndexById(id);
+ return ResponseEntity.noContent()
.headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString()))
.build();
}
/**
- * {@code SEARCH /_search/preferences?query=:query} : search for the preferences corresponding
+ * {@code SEARCH /preferences/_search?query=:query} : search for the preferences corresponding
* to the query.
*
* @param query the query of the preferences search.
* @return the result of the search.
*/
- @GetMapping("/_search/preferences")
- public List searchPreferences(@RequestParam String query) {
+ @GetMapping("/_search")
+ public List searchPreferences(@RequestParam("query") String query) {
log.debug("REST request to search Preferences for query {}", query);
- BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery().must(queryStringQuery(query));
if (SecurityUtils.isAuthenticated() && !SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.ADMIN)) {
- queryBuilder = queryBuilder.filter(matchQuery("user.login", SecurityUtils.getCurrentUserLogin().orElse("")));
+ QueryVariant filterByUser = new MatchQuery.Builder()
+ .field("user.login")
+ .query(SecurityUtils.getCurrentUserLogin().orElse(""))
+ .build();
+ BoolQuery.Builder boolQueryBuilder = QueryBuilders.bool();
+ boolQueryBuilder.should(new Query(filterByUser));
+ query = new Query(boolQueryBuilder.build()).toString();
+ }
+ try {
+ return StreamSupport.stream(preferencesSearchRepository.search(query).spliterator(), false).toList();
+ } catch (RuntimeException e) {
+ throw ElasticsearchExceptionMapper.mapException(e);
}
- return StreamSupport.stream(preferencesSearchRepository.search(queryBuilder).spliterator(), false).collect(Collectors.toList());
}
/**
- * {@code GET /my-preferences} : get the current user's preferences
+ * {@code GET /user} : get the current user's preferences
*
* @return the preferences or default (weeklyGoal: 10) if none exist.
*/
- @GetMapping("/my-preferences")
+ @GetMapping("/user")
public ResponseEntity getUserPreferences() {
String username = SecurityUtils.getCurrentUserLogin().orElse("");
log.debug("REST request to get Preferences : {}", username);
diff --git a/src/main/java/org/jhipster/health/web/rest/PublicUserResource.java b/src/main/java/org/jhipster/health/web/rest/PublicUserResource.java
index 20c55b58..2e2308f6 100644
--- a/src/main/java/org/jhipster/health/web/rest/PublicUserResource.java
+++ b/src/main/java/org/jhipster/health/web/rest/PublicUserResource.java
@@ -2,7 +2,6 @@
import java.util.*;
import java.util.Collections;
-import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.jhipster.health.repository.search.UserSearchRepository;
import org.jhipster.health.service.UserService;
@@ -38,13 +37,13 @@ public PublicUserResource(UserSearchRepository userSearchRepository, UserService
}
/**
- * {@code GET /users} : get all users with only the public informations - calling this are allowed for anyone.
+ * {@code GET /users} : get all users with only public information - calling this method is allowed for anyone.
*
* @param pageable the pagination information.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body all users.
*/
@GetMapping("/users")
- public ResponseEntity> getAllPublicUsers(@org.springdoc.api.annotations.ParameterObject Pageable pageable) {
+ public ResponseEntity> getAllPublicUsers(@org.springdoc.core.annotations.ParameterObject Pageable pageable) {
log.debug("REST request to get all public User names");
if (!onlyContainsAllowedProperties(pageable)) {
return ResponseEntity.badRequest().build();
@@ -60,22 +59,13 @@ private boolean onlyContainsAllowedProperties(Pageable pageable) {
}
/**
- * Gets a list of all roles.
- * @return a string list of all roles.
- */
- @GetMapping("/authorities")
- public List getAuthorities() {
- return userService.getAuthorities();
- }
-
- /**
- * {@code SEARCH /_search/users/:query} : search for the User corresponding to the query.
+ * {@code SEARCH /users/_search/:query} : search for the User corresponding to the query.
*
* @param query the query to search.
* @return the result of the search.
*/
- @GetMapping("/_search/users/{query}")
- public List search(@PathVariable String query) {
- return StreamSupport.stream(userSearchRepository.search(query).spliterator(), false).map(UserDTO::new).collect(Collectors.toList());
+ @GetMapping("/users/_search/{query}")
+ public List search(@PathVariable("query") String query) {
+ return StreamSupport.stream(userSearchRepository.search(query).spliterator(), false).map(UserDTO::new).toList();
}
}
diff --git a/src/main/java/org/jhipster/health/web/rest/UserJWTController.java b/src/main/java/org/jhipster/health/web/rest/UserJWTController.java
deleted file mode 100644
index 1c7e25f9..00000000
--- a/src/main/java/org/jhipster/health/web/rest/UserJWTController.java
+++ /dev/null
@@ -1,68 +0,0 @@
-package org.jhipster.health.web.rest;
-
-import com.fasterxml.jackson.annotation.JsonProperty;
-import javax.validation.Valid;
-import org.jhipster.health.security.jwt.JWTFilter;
-import org.jhipster.health.security.jwt.TokenProvider;
-import org.jhipster.health.web.rest.vm.LoginVM;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.ResponseEntity;
-import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
-import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.context.SecurityContextHolder;
-import org.springframework.web.bind.annotation.*;
-
-/**
- * Controller to authenticate users.
- */
-@RestController
-@RequestMapping("/api")
-public class UserJWTController {
-
- 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.
- */
- static class JWTToken {
-
- private String idToken;
-
- JWTToken(String idToken) {
- this.idToken = idToken;
- }
-
- @JsonProperty("id_token")
- String getIdToken() {
- return idToken;
- }
-
- void setIdToken(String idToken) {
- this.idToken = idToken;
- }
- }
-}
diff --git a/src/main/java/org/jhipster/health/web/rest/UserResource.java b/src/main/java/org/jhipster/health/web/rest/UserResource.java
index 86adcecd..8660c9a5 100644
--- a/src/main/java/org/jhipster/health/web/rest/UserResource.java
+++ b/src/main/java/org/jhipster/health/web/rest/UserResource.java
@@ -1,11 +1,11 @@
package org.jhipster.health.web.rest;
+import jakarta.validation.Valid;
+import jakarta.validation.constraints.Pattern;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.Collections;
-import javax.validation.Valid;
-import javax.validation.constraints.Pattern;
import org.jhipster.health.config.Constants;
import org.jhipster.health.domain.User;
import org.jhipster.health.repository.UserRepository;
@@ -120,8 +120,7 @@ public ResponseEntity createUser(@Valid @RequestBody AdminUserDTO userDTO)
} else {
User newUser = userService.createUser(userDTO);
mailService.sendCreationEmail(newUser);
- return ResponseEntity
- .created(new URI("/api/admin/users/" + newUser.getLogin()))
+ return ResponseEntity.created(new URI("/api/admin/users/" + newUser.getLogin()))
.headers(HeaderUtil.createAlert(applicationName, "userManagement.created", newUser.getLogin()))
.body(newUser);
}
@@ -135,16 +134,19 @@ public ResponseEntity createUser(@Valid @RequestBody AdminUserDTO userDTO)
* @throws EmailAlreadyUsedException {@code 400 (Bad Request)} if the email is already in use.
* @throws LoginAlreadyUsedException {@code 400 (Bad Request)} if the login is already in use.
*/
- @PutMapping("/users")
+ @PutMapping({ "/users", "/users/{login}" })
@PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")")
- public ResponseEntity updateUser(@Valid @RequestBody AdminUserDTO userDTO) {
+ public ResponseEntity updateUser(
+ @PathVariable(name = "login", required = false) @Pattern(regexp = Constants.LOGIN_REGEX) String login,
+ @Valid @RequestBody AdminUserDTO userDTO
+ ) {
log.debug("REST request to update User : {}", userDTO);
Optional existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail());
- if (existingUser.isPresent() && (!existingUser.get().getId().equals(userDTO.getId()))) {
+ if (existingUser.isPresent() && (!existingUser.orElseThrow().getId().equals(userDTO.getId()))) {
throw new EmailAlreadyUsedException();
}
existingUser = userRepository.findOneByLogin(userDTO.getLogin().toLowerCase());
- if (existingUser.isPresent() && (!existingUser.get().getId().equals(userDTO.getId()))) {
+ if (existingUser.isPresent() && (!existingUser.orElseThrow().getId().equals(userDTO.getId()))) {
throw new LoginAlreadyUsedException();
}
Optional updatedUser = userService.updateUser(userDTO);
@@ -163,7 +165,7 @@ public ResponseEntity updateUser(@Valid @RequestBody AdminUserDTO
*/
@GetMapping("/users")
@PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")")
- public ResponseEntity> getAllUsers(@org.springdoc.api.annotations.ParameterObject Pageable pageable) {
+ public ResponseEntity> getAllUsers(@org.springdoc.core.annotations.ParameterObject Pageable pageable) {
log.debug("REST request to get all User for an admin");
if (!onlyContainsAllowedProperties(pageable)) {
return ResponseEntity.badRequest().build();
@@ -186,7 +188,7 @@ private boolean onlyContainsAllowedProperties(Pageable pageable) {
*/
@GetMapping("/users/{login}")
@PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")")
- public ResponseEntity getUser(@PathVariable @Pattern(regexp = Constants.LOGIN_REGEX) String login) {
+ public ResponseEntity getUser(@PathVariable("login") @Pattern(regexp = Constants.LOGIN_REGEX) String login) {
log.debug("REST request to get User : {}", login);
return ResponseUtil.wrapOrNotFound(userService.getUserWithAuthoritiesByLogin(login).map(AdminUserDTO::new));
}
@@ -199,7 +201,7 @@ public ResponseEntity getUser(@PathVariable @Pattern(regexp = Cons
*/
@DeleteMapping("/users/{login}")
@PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")")
- public ResponseEntity deleteUser(@PathVariable @Pattern(regexp = Constants.LOGIN_REGEX) String login) {
+ public ResponseEntity deleteUser(@PathVariable("login") @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, "userManagement.deleted", login)).build();
diff --git a/src/main/java/org/jhipster/health/web/rest/WeightResource.java b/src/main/java/org/jhipster/health/web/rest/WeightResource.java
index 12dcd914..163648d2 100644
--- a/src/main/java/org/jhipster/health/web/rest/WeightResource.java
+++ b/src/main/java/org/jhipster/health/web/rest/WeightResource.java
@@ -1,25 +1,17 @@
package org.jhipster.health.web.rest;
-import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
-import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery;
-
+import co.elastic.clients.elasticsearch._types.query_dsl.*;
+import jakarta.validation.Valid;
+import jakarta.validation.constraints.NotNull;
import java.net.URI;
import java.net.URISyntaxException;
-import java.time.LocalDate;
-import java.time.YearMonth;
-import java.time.ZoneId;
-import java.time.ZoneOffset;
-import java.time.ZonedDateTime;
+import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
-import javax.validation.Valid;
-import javax.validation.constraints.NotNull;
-import org.elasticsearch.index.query.BoolQueryBuilder;
-import org.elasticsearch.index.query.QueryBuilders;
import org.jhipster.health.domain.Weight;
import org.jhipster.health.repository.UserRepository;
import org.jhipster.health.repository.WeightRepository;
@@ -27,6 +19,7 @@
import org.jhipster.health.security.AuthoritiesConstants;
import org.jhipster.health.security.SecurityUtils;
import org.jhipster.health.web.rest.errors.BadRequestAlertException;
+import org.jhipster.health.web.rest.errors.ElasticsearchExceptionMapper;
import org.jhipster.health.web.rest.vm.WeightByPeriod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -48,7 +41,7 @@
* REST controller for managing {@link org.jhipster.health.domain.Weight}.
*/
@RestController
-@RequestMapping("/api")
+@RequestMapping("/api/weights")
@Transactional
public class WeightResource {
@@ -78,7 +71,7 @@ public WeightResource(WeightRepository weightRepository, WeightSearchRepository
* @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new weight, or with status {@code 400 (Bad Request)} if the weight has already an ID.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
- @PostMapping("/weights")
+ @PostMapping("")
public ResponseEntity createWeight(@Valid @RequestBody Weight weight) throws URISyntaxException {
log.debug("REST request to save Weight : {}", weight);
if (weight.getId() != null) {
@@ -88,25 +81,24 @@ public ResponseEntity createWeight(@Valid @RequestBody Weight weight) th
log.debug("No user passed in, using current user: {}", SecurityUtils.getCurrentUserLogin().orElse(""));
weight.setUser(userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin().orElse("")).orElse(null));
}
- Weight result = weightRepository.save(weight);
- weightSearchRepository.index(result);
- return ResponseEntity
- .created(new URI("/api/weights/" + result.getId()))
- .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
- .body(result);
+ weight = weightRepository.save(weight);
+ weightSearchRepository.index(weight);
+ return ResponseEntity.created(new URI("/api/weights/" + weight.getId()))
+ .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, weight.getId().toString()))
+ .body(weight);
}
/**
* {@code PUT /weights/:id} : Updates an existing weight.
*
- * @param id the id of the weight to save.
+ * @param id the id of the weight to save.
* @param weight the weight to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated weight,
* or with status {@code 400 (Bad Request)} if the weight is not valid,
* or with status {@code 500 (Internal Server Error)} if the weight couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
- @PutMapping("/weights/{id}")
+ @PutMapping("/{id}")
public ResponseEntity> updateWeight(@PathVariable(value = "id", required = false) final Long id, @Valid @RequestBody Weight weight)
throws URISyntaxException {
log.debug("REST request to update Weight : {}, {}", id, weight);
@@ -127,18 +119,17 @@ public ResponseEntity> updateWeight(@PathVariable(value = "id", required = fal
return new ResponseEntity<>("error.http.403", HttpStatus.FORBIDDEN);
}
- Weight result = weightRepository.save(weight);
- weightSearchRepository.index(result);
- return ResponseEntity
- .ok()
+ weight = weightRepository.save(weight);
+ weightSearchRepository.index(weight);
+ return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, weight.getId().toString()))
- .body(result);
+ .body(weight);
}
/**
* {@code PATCH /weights/:id} : Partial updates given fields of an existing weight, field will ignore if it is null
*
- * @param id the id of the weight to save.
+ * @param id the id of the weight to save.
* @param weight the weight to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated weight,
* or with status {@code 400 (Bad Request)} if the weight is not valid,
@@ -146,7 +137,7 @@ public ResponseEntity> updateWeight(@PathVariable(value = "id", required = fal
* or with status {@code 500 (Internal Server Error)} if the weight couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
- @PatchMapping(value = "/weights/{id}", consumes = { "application/json", "application/merge-patch+json" })
+ @PatchMapping(value = "/{id}", consumes = { "application/json", "application/merge-patch+json" })
public ResponseEntity> partialUpdateWeight(
@PathVariable(value = "id", required = false) final Long id,
@NotNull @RequestBody Weight weight
@@ -183,8 +174,7 @@ public ResponseEntity> partialUpdateWeight(
})
.map(weightRepository::save)
.map(savedWeight -> {
- weightSearchRepository.save(savedWeight);
-
+ weightSearchRepository.index(savedWeight);
return savedWeight;
});
@@ -197,19 +187,23 @@ public ResponseEntity> partialUpdateWeight(
/**
* {@code GET /weights} : get all the weights.
*
- * @param pageable the pagination information.
+ * @param pageable the pagination information.
* @param eagerload flag to eager load entities from relationships (This is applicable for many-to-many).
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of weights in body.
*/
- @GetMapping("/weights")
+ @GetMapping("")
public ResponseEntity> getAllWeights(
- @org.springdoc.api.annotations.ParameterObject Pageable pageable,
- @RequestParam(required = false, defaultValue = "false") boolean eagerload
+ @org.springdoc.core.annotations.ParameterObject Pageable pageable,
+ @RequestParam(name = "eagerload", required = false, defaultValue = "true") boolean eagerload
) {
log.debug("REST request to get a page of Weights");
Page page;
if (SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.ADMIN)) {
- page = weightRepository.findAllByOrderByTimestampDesc(pageable);
+ if (eagerload) {
+ page = weightRepository.findAllWithEagerRelationships(pageable);
+ } else {
+ page = weightRepository.findAll(pageable);
+ }
} else {
page = weightRepository.findByUserIsCurrentUser(pageable);
}
@@ -223,8 +217,8 @@ public ResponseEntity> getAllWeights(
* @param id the id of the weight to retrieve.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the weight, or with status {@code 404 (Not Found)}.
*/
- @GetMapping("/weights/{id}")
- public ResponseEntity> getWeight(@PathVariable Long id) {
+ @GetMapping("/{id}")
+ public ResponseEntity> getWeight(@PathVariable("id") Long id) {
log.debug("REST request to get Weight : {}", id);
Optional weight = weightRepository.findOneWithEagerRelationships(id);
if (
@@ -244,8 +238,8 @@ public ResponseEntity> getWeight(@PathVariable Long id) {
* @param id the id of the weight to delete.
* @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
*/
- @DeleteMapping("/weights/{id}")
- public ResponseEntity> deleteWeight(@PathVariable Long id) {
+ @DeleteMapping("/{id}")
+ public ResponseEntity> deleteWeight(@PathVariable("id") Long id) {
log.debug("REST request to delete Weight : {}", id);
Optional weight = weightRepository.findById(id);
if (
@@ -257,43 +251,51 @@ public ResponseEntity> deleteWeight(@PathVariable Long id) {
return new ResponseEntity<>("error.http.403", HttpStatus.FORBIDDEN);
}
weightRepository.deleteById(id);
- weightSearchRepository.deleteById(id);
- return ResponseEntity
- .noContent()
+ weightSearchRepository.deleteFromIndexById(id);
+ return ResponseEntity.noContent()
.headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString()))
.build();
}
/**
- * {@code SEARCH /_search/weights?query=:query} : search for the weight corresponding
+ * {@code SEARCH /weights/_search?query=:query} : search for the weight corresponding
* to the query.
*
- * @param query the query of the weight search.
+ * @param query the query of the weight search.
* @param pageable the pagination information.
* @return the result of the search.
*/
- @GetMapping("/_search/weights")
+ @GetMapping("/_search")
public ResponseEntity> searchWeights(
- @RequestParam String query,
- @org.springdoc.api.annotations.ParameterObject Pageable pageable
+ @RequestParam("query") String query,
+ @org.springdoc.core.annotations.ParameterObject Pageable pageable
) {
log.debug("REST request to search for a page of Weights for query {}", query);
- BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery().must(queryStringQuery(query));
if (SecurityUtils.isAuthenticated() && !SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.ADMIN)) {
- queryBuilder = queryBuilder.filter(matchQuery("user.login", SecurityUtils.getCurrentUserLogin().orElse("")));
+ QueryVariant filterByUser = new MatchQuery.Builder()
+ .field("user.login")
+ .query(SecurityUtils.getCurrentUserLogin().orElse(""))
+ .build();
+ BoolQuery.Builder boolQueryBuilder = QueryBuilders.bool();
+ boolQueryBuilder.should(new Query(filterByUser));
+ query = new Query(boolQueryBuilder.build()).toString();
+ }
+ try {
+ Page page = weightSearchRepository.search(query, pageable);
+ HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
+ return ResponseEntity.ok().headers(headers).body(page.getContent());
+ } catch (RuntimeException e) {
+ throw ElasticsearchExceptionMapper.mapException(e);
}
- Page page = weightSearchRepository.search(queryBuilder, pageable);
- HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
- return ResponseEntity.ok().headers(headers).body(page.getContent());
}
/**
- * {@code GET /weight-by-days} : get all the weigh-ins for last x days.
+ * {@code GET /weights/by-days} : get all the weigh-ins for last x days.
*
* @param days the days to fetch the results for.
* @return the result of the search.
*/
- @GetMapping("/weight-by-days/{days}")
+ @GetMapping("/by-days/{days}")
public ResponseEntity getByDays(@PathVariable int days) {
ZonedDateTime rightNow = ZonedDateTime.now(ZoneOffset.UTC);
ZonedDateTime daysAgo = rightNow.minusDays(days);
@@ -304,12 +306,12 @@ public ResponseEntity getByDays(@PathVariable int days) {
}
/**
- * {@code GET /weight-by-month/:date} : get all the blood pressure readings for a particular month.
+ * {@code GET /weights/by-month/:date} : get all the blood pressure readings for a particular month.
*
* @param date the month to fetch results for.
* @return the result of the search.
*/
- @GetMapping("/weight-by-month/{date}")
+ @GetMapping("/by-month/{date}")
public ResponseEntity getByMonth(@PathVariable @DateTimeFormat(pattern = "yyyy-MM") YearMonth date) {
LocalDate firstDay = date.atDay(1);
LocalDate lastDay = date.atEndOfMonth();
diff --git a/src/main/java/org/jhipster/health/web/rest/errors/BadRequestAlertException.java b/src/main/java/org/jhipster/health/web/rest/errors/BadRequestAlertException.java
index 4f5018e1..119d27af 100644
--- a/src/main/java/org/jhipster/health/web/rest/errors/BadRequestAlertException.java
+++ b/src/main/java/org/jhipster/health/web/rest/errors/BadRequestAlertException.java
@@ -1,13 +1,13 @@
package org.jhipster.health.web.rest.errors;
import java.net.URI;
-import java.util.HashMap;
-import java.util.Map;
-import org.zalando.problem.AbstractThrowableProblem;
-import org.zalando.problem.Status;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.ErrorResponseException;
+import tech.jhipster.web.rest.errors.ProblemDetailWithCause;
+import tech.jhipster.web.rest.errors.ProblemDetailWithCause.ProblemDetailWithCauseBuilder;
@SuppressWarnings("java:S110") // Inheritance tree of classes should not be too deep
-public class BadRequestAlertException extends AbstractThrowableProblem {
+public class BadRequestAlertException extends ErrorResponseException {
private static final long serialVersionUID = 1L;
@@ -20,7 +20,17 @@ public BadRequestAlertException(String defaultMessage, String entityName, String
}
public BadRequestAlertException(URI type, String defaultMessage, String entityName, String errorKey) {
- super(type, defaultMessage, Status.BAD_REQUEST, null, null, null, getAlertParameters(entityName, errorKey));
+ super(
+ HttpStatus.BAD_REQUEST,
+ ProblemDetailWithCauseBuilder.instance()
+ .withStatus(HttpStatus.BAD_REQUEST.value())
+ .withType(type)
+ .withTitle(defaultMessage)
+ .withProperty("message", "error." + errorKey)
+ .withProperty("params", entityName)
+ .build(),
+ null
+ );
this.entityName = entityName;
this.errorKey = errorKey;
}
@@ -33,10 +43,7 @@ public String getErrorKey() {
return errorKey;
}
- private static Map getAlertParameters(String entityName, String errorKey) {
- Map parameters = new HashMap<>();
- parameters.put("message", "error." + errorKey);
- parameters.put("params", entityName);
- return parameters;
+ public ProblemDetailWithCause getProblemDetailWithCause() {
+ return (ProblemDetailWithCause) this.getBody();
}
}
diff --git a/src/main/java/org/jhipster/health/web/rest/errors/ElasticsearchExceptionMapper.java b/src/main/java/org/jhipster/health/web/rest/errors/ElasticsearchExceptionMapper.java
new file mode 100644
index 00000000..2f29221c
--- /dev/null
+++ b/src/main/java/org/jhipster/health/web/rest/errors/ElasticsearchExceptionMapper.java
@@ -0,0 +1,30 @@
+package org.jhipster.health.web.rest.errors;
+
+import co.elastic.clients.elasticsearch._types.ElasticsearchException;
+import co.elastic.clients.elasticsearch._types.ErrorCause;
+import java.util.List;
+import org.springframework.data.elasticsearch.UncategorizedElasticsearchException;
+
+public class ElasticsearchExceptionMapper {
+
+ private ElasticsearchExceptionMapper() {}
+
+ public static RuntimeException mapException(RuntimeException originalException) {
+ RuntimeException e = originalException;
+ if (e.getCause() instanceof UncategorizedElasticsearchException) {
+ e = (UncategorizedElasticsearchException) e.getCause();
+ }
+ if (e.getCause() instanceof ElasticsearchException) {
+ ElasticsearchException esException = (ElasticsearchException) e.getCause();
+ List rootCause = esException.response().error().rootCause();
+ if (!rootCause.isEmpty()) {
+ String reason = rootCause.get(0).reason();
+ if (reason != null && reason.startsWith("Failed to parse query [")) {
+ return new QuerySyntaxException();
+ }
+ }
+ }
+
+ return originalException;
+ }
+}
diff --git a/src/main/java/org/jhipster/health/web/rest/errors/ExceptionTranslator.java b/src/main/java/org/jhipster/health/web/rest/errors/ExceptionTranslator.java
index e5bf1085..3398ec81 100644
--- a/src/main/java/org/jhipster/health/web/rest/errors/ExceptionTranslator.java
+++ b/src/main/java/org/jhipster/health/web/rest/errors/ExceptionTranslator.java
@@ -1,35 +1,39 @@
package org.jhipster.health.web.rest.errors;
+import static org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotation;
+
+import jakarta.servlet.http.HttpServletRequest;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
+import java.util.Map;
import java.util.Optional;
-import java.util.stream.Collectors;
-import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
-import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.dao.DataAccessException;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConversionException;
-import org.springframework.validation.BindingResult;
+import org.springframework.lang.Nullable;
+import org.springframework.security.access.AccessDeniedException;
+import org.springframework.security.authentication.BadCredentialsException;
+import org.springframework.web.ErrorResponse;
+import org.springframework.web.ErrorResponseException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.NativeWebRequest;
-import org.zalando.problem.DefaultProblem;
-import org.zalando.problem.Problem;
-import org.zalando.problem.ProblemBuilder;
-import org.zalando.problem.Status;
-import org.zalando.problem.StatusType;
-import org.zalando.problem.spring.web.advice.ProblemHandling;
-import org.zalando.problem.spring.web.advice.security.SecurityAdviceTrait;
-import org.zalando.problem.violations.ConstraintViolationProblem;
+import org.springframework.web.context.request.WebRequest;
+import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import tech.jhipster.config.JHipsterConstants;
+import tech.jhipster.web.rest.errors.ProblemDetailWithCause;
+import tech.jhipster.web.rest.errors.ProblemDetailWithCause.ProblemDetailWithCauseBuilder;
import tech.jhipster.web.util.HeaderUtil;
/**
@@ -37,12 +41,12 @@
* The error response follows RFC7807 - Problem Details for HTTP APIs (https://tools.ietf.org/html/rfc7807).
*/
@ControllerAdvice
-public class ExceptionTranslator implements ProblemHandling, SecurityAdviceTrait {
+public class ExceptionTranslator extends ResponseEntityExceptionHandler {
private static final String FIELD_ERRORS_KEY = "fieldErrors";
private static final String MESSAGE_KEY = "message";
private static final String PATH_KEY = "path";
- private static final String VIOLATIONS_KEY = "violations";
+ private static final boolean CASUAL_CHAIN_ENABLED = false;
@Value("${jhipster.clientApp.name}")
private String applicationName;
@@ -53,170 +57,197 @@ public ExceptionTranslator(Environment env) {
this.env = env;
}
- /**
- * Post-process the Problem payload to add the message key for the front-end if needed.
- */
+ @ExceptionHandler
+ public ResponseEntity