Skip to content
This repository has been archived by the owner on Dec 5, 2023. It is now read-only.

Commit

Permalink
🎨 enable spring-javaformat-maven-plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
zhouhao committed Apr 1, 2023
1 parent 20ff426 commit cae3a25
Show file tree
Hide file tree
Showing 55 changed files with 498 additions and 505 deletions.
1 change: 1 addition & 0 deletions .springjavaformatconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
indentation-style=spaces
8 changes: 6 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
</parent>
<groupId>com.saltynote</groupId>
<artifactId>service</artifactId>
<version>0.3.0</version>
<version>0.3.1</version>
<name>saltynote-service</name>
<description>Backend service for saltynote</description>

Expand Down Expand Up @@ -166,7 +166,6 @@
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
<!-- MapStruct 和 Lombok 注解绑定处理器 -->
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-mapstruct-binding</artifactId>
Expand Down Expand Up @@ -201,6 +200,11 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>io.spring.javaformat</groupId>
<artifactId>spring-javaformat-maven-plugin</artifactId>
<version>0.0.38</version>
</plugin>
</plugins>
</build>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@ public static void main(String[] args) {
public ObjectMapper objectMapper() {
return new ObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,5 @@ public Object logServiceAccess(ProceedingJoinPoint pjp) throws Throwable {
log.info(pjp.getSignature() + " execution time: " + elapsedTime + " milliseconds.");
return output;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@ public class HomeController {
public ResponseEntity<ServiceResponse> home() {
return ResponseEntity.ok(ServiceResponse.ok(welcomeMessage));
}

}
41 changes: 19 additions & 22 deletions src/main/java/com/saltynote/service/controller/NoteController.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@
@RestController
@Slf4j
public class NoteController {

private final NoteService noteService;

private final NoteConverter noteConverter;

public NoteController(NoteService noteService, NoteConverter noteConverter) {
Expand All @@ -47,11 +49,9 @@ public ResponseEntity<Note> getNoteById(@PathVariable("id") String id, Authentic
return note.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build());
}

@RequestMapping(
value = "/note/{id}",
method = {RequestMethod.POST, RequestMethod.PUT})
public ResponseEntity<Note> updateNoteById(
@PathVariable("id") String id, @RequestBody NoteDto noteDto, Authentication auth) {
@RequestMapping(value = "/note/{id}", method = { RequestMethod.POST, RequestMethod.PUT })
public ResponseEntity<Note> updateNoteById(@PathVariable("id") String id, @RequestBody NoteDto noteDto,
Authentication auth) {
Optional<Note> queryNote = noteService.getRepository().findById(id);
checkNoteOwner(queryNote, auth);
Note noteTobeUpdate = queryNote.get();
Expand All @@ -71,19 +71,18 @@ public ResponseEntity<Note> updateNoteById(
}

@DeleteMapping("/note/{id}")
public ResponseEntity<ServiceResponse> deleteNoteById(
@PathVariable("id") String id, Authentication auth) {
public ResponseEntity<ServiceResponse> deleteNoteById(@PathVariable("id") String id, Authentication auth) {
Optional<Note> note = noteService.getRepository().findById(id);
checkNoteOwner(note, auth);
noteService.getRepository().deleteById(id);
return ResponseEntity.ok(ServiceResponse.ok("Delete Successfully!"));
}

// TODO: this POST is required for chrome extension, as I find the PUT or DELETE requests will be
// TODO: this POST is required for chrome extension, as I find the PUT or DELETE
// requests will be
// blocked by Chrome. Further investigation is required from me for this issue.
@PostMapping("/note/{id}/delete")
public ResponseEntity<ServiceResponse> postDeleteNoteById(
@PathVariable("id") String id, Authentication auth) {
public ResponseEntity<ServiceResponse> postDeleteNoteById(@PathVariable("id") String id, Authentication auth) {
return deleteNoteById(id, auth);
}

Expand All @@ -94,14 +93,12 @@ public List<Note> getNotes(Authentication auth, @RequestParam(required = false)
if (allNotes == null || allNotes.isEmpty() || StringUtils.isBlank(keyword)) {
return allNotes;
}
Iterable<String> queries = Splitter.on(" ")
.trimResults()
.omitEmptyStrings()
.split(keyword);

return allNotes.stream().filter(n -> StringUtils.isNotBlank(n.getNote()) && BaseUtils.containsAllIgnoreCase(n.getNote(), queries) ||
StringUtils.isNotBlank(n.getText()) && BaseUtils.containsAllIgnoreCase(n.getText(), queries))
.toList();
Iterable<String> queries = Splitter.on(" ").trimResults().omitEmptyStrings().split(keyword);

return allNotes.stream()
.filter(n -> StringUtils.isNotBlank(n.getNote()) && BaseUtils.containsAllIgnoreCase(n.getNote(), queries)
|| StringUtils.isNotBlank(n.getText()) && BaseUtils.containsAllIgnoreCase(n.getText(), queries))
.toList();
}

@PostMapping("/notes")
Expand All @@ -119,16 +116,16 @@ public ResponseEntity<Note> createNote(@Valid @RequestBody NoteDto noteDto, Auth
if (StringUtils.isNotBlank(note.getId())) {
return ResponseEntity.ok(note);
}
throw new WebAppRuntimeException(
HttpStatus.INTERNAL_SERVER_ERROR, "Failed to save note into database: " + note);
throw new WebAppRuntimeException(HttpStatus.INTERNAL_SERVER_ERROR,
"Failed to save note into database: " + note);
}

private void checkNoteOwner(Optional<Note> note, Authentication auth) {
JwtUser user = (JwtUser) auth.getPrincipal();
if (note.isPresent() && user.getId().equals(note.get().getUserId())) {
return;
}
throw new WebAppRuntimeException(
HttpStatus.FORBIDDEN, "Permission Error: You are not the owner of the note.");
throw new WebAppRuntimeException(HttpStatus.FORBIDDEN, "Permission Error: You are not the owner of the note.");
}

}
60 changes: 36 additions & 24 deletions src/main/java/com/saltynote/service/controller/UserController.java
Original file line number Diff line number Diff line change
Expand Up @@ -49,17 +49,23 @@ public class UserController {
private int passwordMinimalLength;

private final UserService userService;

private final BCryptPasswordEncoder bCryptPasswordEncoder;

private final JwtService jwtService;

private final ApplicationEventPublisher eventPublisher;

private final VaultService vaultService;

private final JWTAuthenticationService authenticationService;

@PostMapping("/email/verification")
public ResponseEntity<ServiceResponse> getVerificationToken(@Valid @RequestBody Payload payload) {
// check whether this email is already signed up or not.
if (userService.getRepository().findByEmail(payload.getEmail()).isPresent()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ServiceResponse(HttpStatus.BAD_REQUEST, "Email is already signed up."));
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(new ServiceResponse(HttpStatus.BAD_REQUEST, "Email is already signed up."));
}

SiteUser user = new SiteUser().setEmail(payload.getEmail()).setUsername("there");
Expand All @@ -70,29 +76,27 @@ public ResponseEntity<ServiceResponse> getVerificationToken(@Valid @RequestBody
@PostMapping("/signup")
public ResponseEntity<JwtUser> signup(@Valid @RequestBody UserNewRequest userNewRequest) {
if (userNewRequest.getPassword().length() < passwordMinimalLength) {
throw new WebAppRuntimeException(HttpStatus.BAD_REQUEST, "Password should be at least " + passwordMinimalLength + " characters.");
throw new WebAppRuntimeException(HttpStatus.BAD_REQUEST,
"Password should be at least " + passwordMinimalLength + " characters.");
}
// Check token
Optional<Vault> vaultOp =
vaultService
.getRepository()
.findByEmailAndSecretAndType(
userNewRequest.getEmail(),
userNewRequest.getToken(),
VaultType.NEW_ACCOUNT.getValue());
Optional<Vault> vaultOp = vaultService.getRepository()
.findByEmailAndSecretAndType(userNewRequest.getEmail(), userNewRequest.getToken(),
VaultType.NEW_ACCOUNT.getValue());

if (vaultOp.isEmpty()) {
throw new WebAppRuntimeException(
HttpStatus.FORBIDDEN, "A valid verification code is required for signup.");
throw new WebAppRuntimeException(HttpStatus.FORBIDDEN, "A valid verification code is required for signup.");
}
SiteUser user = userNewRequest.toSiteUser();
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
user = userService.getRepository().save(user);
if (StringUtils.hasText(user.getId())) {
vaultService.getRepository().delete(vaultOp.get());
return ResponseEntity.ok(new JwtUser(user.getId(), user.getUsername()));
} else {
throw new WebAppRuntimeException(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to signup, please try again later.");
}
else {
throw new WebAppRuntimeException(HttpStatus.INTERNAL_SERVER_ERROR,
"Failed to signup, please try again later.");
}
}

Expand All @@ -106,11 +110,13 @@ public ResponseEntity<JwtToken> refreshToken(@Valid @RequestBody JwtToken jwtTok
// 1. No expiry, and valid.
JwtUser user = jwtService.parseRefreshToken(jwtToken.getRefreshToken());
// 2. Not deleted from database.
Optional<Vault> token = vaultService.findByUserIdAndTypeAndValue(user.getId(), VaultType.REFRESH_TOKEN, jwtToken.getRefreshToken());
Optional<Vault> token = vaultService.findByUserIdAndTypeAndValue(user.getId(), VaultType.REFRESH_TOKEN,
jwtToken.getRefreshToken());
if (token.isPresent()) {
String newToken = jwtService.createAccessToken(user);
return ResponseEntity.ok(new JwtToken(newToken, jwtToken.getRefreshToken()));
} else {
}
else {
throw new WebAppRuntimeException(HttpStatus.BAD_REQUEST, "Invalid refresh token provided!");
}
}
Expand All @@ -129,18 +135,21 @@ public ResponseEntity<ServiceResponse> forgetPassword(@Valid @RequestBody Payloa
Optional<SiteUser> usero = userService.getRepository().findByEmail(payload.getEmail());
if (usero.isEmpty()) {
log.warn("User is not found for email = {}", payload.getEmail());
return ResponseEntity.status(HttpStatus.PRECONDITION_FAILED).body(new ServiceResponse(HttpStatus.PRECONDITION_FAILED, "Invalid email"));
return ResponseEntity.status(HttpStatus.PRECONDITION_FAILED)
.body(new ServiceResponse(HttpStatus.PRECONDITION_FAILED, "Invalid email"));
}

eventPublisher.publishEvent(new EmailEvent(this, usero.get(), EmailEvent.Type.PASSWORD_FORGET));
return ResponseEntity.ok(ServiceResponse.ok("Password reset email will be sent to your email, please reset your email with link there."));
return ResponseEntity.ok(ServiceResponse
.ok("Password reset email will be sent to your email, please reset your email with link there."));
}

@PostMapping("/password/reset")
public ResponseEntity<ServiceResponse> resetPassword(@Valid @RequestBody PasswordReset passwordReset) {
val wre = new WebAppRuntimeException(HttpStatus.BAD_REQUEST, "Invalid payload provided.");
if (passwordReset.getPassword().length() < passwordMinimalLength) {
throw new WebAppRuntimeException(HttpStatus.BAD_REQUEST, "Password should be at least " + passwordMinimalLength + " characters.");
throw new WebAppRuntimeException(HttpStatus.BAD_REQUEST,
"Password should be at least " + passwordMinimalLength + " characters.");
}
Optional<Vault> vo = vaultService.findByToken(passwordReset.getToken());
if (vo.isEmpty()) {
Expand All @@ -154,23 +163,27 @@ public ResponseEntity<ServiceResponse> resetPassword(@Valid @RequestBody Passwor
userService.getRepository().save(user);
vaultService.getRepository().delete(vo.get());
return ResponseEntity.ok(ServiceResponse.ok("Password has been reset!"));
} else {
}
else {
throw wre;
}
}

@RequestMapping(value = "/password", method = {RequestMethod.POST, RequestMethod.PUT})
public ResponseEntity<ServiceResponse> updatePassword(@Valid @RequestBody PasswordUpdate passwordUpdate, Authentication auth) {
@RequestMapping(value = "/password", method = { RequestMethod.POST, RequestMethod.PUT })
public ResponseEntity<ServiceResponse> updatePassword(@Valid @RequestBody PasswordUpdate passwordUpdate,
Authentication auth) {
JwtUser jwtUser = (JwtUser) auth.getPrincipal();
// Validate new password
if (passwordUpdate.getPassword().length() < passwordMinimalLength) {
throw new WebAppRuntimeException(HttpStatus.BAD_REQUEST, "New password should be at least " + passwordMinimalLength + " characters.");
throw new WebAppRuntimeException(HttpStatus.BAD_REQUEST,
"New password should be at least " + passwordMinimalLength + " characters.");
}

// Validate old password
Optional<SiteUser> usero = userService.getRepository().findById(jwtUser.getId());
if (usero.isEmpty()) {
throw new WebAppRuntimeException(HttpStatus.BAD_REQUEST, "Something goes wrong when fetching your info, please try later again.");
throw new WebAppRuntimeException(HttpStatus.BAD_REQUEST,
"Something goes wrong when fetching your info, please try later again.");
}
SiteUser user = usero.get();
if (!bCryptPasswordEncoder.matches(passwordUpdate.getOldPassword(), user.getPassword())) {
Expand All @@ -182,7 +195,6 @@ public ResponseEntity<ServiceResponse> updatePassword(@Valid @RequestBody Passwo
return ResponseEntity.ok(ServiceResponse.ok("Password is updated now."));
}


@DeleteMapping("/account/{id}")
public ResponseEntity<ServiceResponse> accountDeletion(@PathVariable("id") String userId, Authentication auth) {
JwtUser jwtUser = (JwtUser) auth.getPrincipal();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,36 +14,30 @@
public class ExceptionHandlerControllerAdvice {

@ExceptionHandler(AuthenticationException.class)
public ResponseEntity<ServiceResponse> handleAuthenticationException(
AuthenticationException e) {
public ResponseEntity<ServiceResponse> handleAuthenticationException(AuthenticationException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body(new ServiceResponse(HttpStatus.UNAUTHORIZED, e.getMessage()));
.body(new ServiceResponse(HttpStatus.UNAUTHORIZED, e.getMessage()));
}

@ExceptionHandler(WebAppRuntimeException.class)
public ResponseEntity<ServiceResponse> handleWebClientRuntimeException(
WebAppRuntimeException e) {
return ResponseEntity.status(e.getStatus())
.body(new ServiceResponse(e.getStatus(), e.getMessage()));
public ResponseEntity<ServiceResponse> handleWebClientRuntimeException(WebAppRuntimeException e) {
return ResponseEntity.status(e.getStatus()).body(new ServiceResponse(e.getStatus(), e.getMessage()));
}

@ExceptionHandler(RuntimeException.class)
public ResponseEntity<ServiceResponse> handleRuntimeException(RuntimeException e) {
log.error(e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(
new ServiceResponse(
HttpStatus.INTERNAL_SERVER_ERROR,
"Something is going wrong with the server, please try again later."));
.body(new ServiceResponse(HttpStatus.INTERNAL_SERVER_ERROR,
"Something is going wrong with the server, please try again later."));
}

@ExceptionHandler(Exception.class)
public ResponseEntity<ServiceResponse> handleRuntimeException(Exception e) {
log.error(e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(
new ServiceResponse(
HttpStatus.BAD_REQUEST,
"Something is going wrong with your request, please try again later."));
.body(new ServiceResponse(HttpStatus.BAD_REQUEST,
"Something is going wrong with your request, please try again later."));
}

}
5 changes: 5 additions & 0 deletions src/main/java/com/saltynote/service/domain/EmailPayload.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,13 @@
@Data
@Accessors(chain = true)
public class EmailPayload {

private String username;

private String message;

private String link;

private String linkText;

}
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package com.saltynote.service.domain;

public interface IdentifiableUser {

String getId();

String getUsername();

}
2 changes: 2 additions & 0 deletions src/main/java/com/saltynote/service/domain/LoginUser.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@
import java.util.Collections;

public class LoginUser extends User implements IdentifiableUser {

@Getter
private final String id;

public LoginUser(SiteUser user) {
super(user.getUsername(), user.getPassword(), Collections.emptyList());
this.id = user.getId();
}

}
3 changes: 3 additions & 0 deletions src/main/java/com/saltynote/service/domain/VaultEntity.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,13 @@
@Data
@Accessors(chain = true)
public class VaultEntity {

private String userId;

private String secret;

public static VaultEntity from(Vault vault) {
return new VaultEntity().setSecret(vault.getSecret()).setUserId(vault.getUserId());
}

}
Loading

0 comments on commit cae3a25

Please sign in to comment.