From 1e752b8bdeb3ca58af9cf0c21d3adf53a3106e35 Mon Sep 17 00:00:00 2001 From: Kaiser-Yang Date: Tue, 24 Sep 2024 11:32:18 +0000 Subject: [PATCH] Apply Google Java Style Format --- .../cmipt/gcs/constant/ApiPathConstant.java | 13 +--- .../edu/cmipt/gcs/constant/GitConstant.java | 3 +- .../gcs/controller/SshKeyController.java | 52 ++++++++----- .../java/edu/cmipt/gcs/filter/JwtFilter.java | 16 ++-- .../edu/cmipt/gcs/pojo/ssh/SshKeyDTO.java | 68 ++++++++--------- .../java/edu/cmipt/gcs/pojo/ssh/SshKeyPO.java | 4 +- .../java/edu/cmipt/gcs/pojo/ssh/SshKeyVO.java | 6 +- .../gcs/service/RepositoryServiceImpl.java | 22 ++++-- .../edu/cmipt/gcs/service/SshKeyService.java | 1 - .../cmipt/gcs/service/SshKeyServiceImpl.java | 53 ++++++++----- .../gcs/controller/SshKeyControllerTest.java | 75 +++++++++++-------- 11 files changed, 184 insertions(+), 129 deletions(-) diff --git a/src/main/java/edu/cmipt/gcs/constant/ApiPathConstant.java b/src/main/java/edu/cmipt/gcs/constant/ApiPathConstant.java index 28383ac..80e2b16 100644 --- a/src/main/java/edu/cmipt/gcs/constant/ApiPathConstant.java +++ b/src/main/java/edu/cmipt/gcs/constant/ApiPathConstant.java @@ -34,13 +34,8 @@ public class ApiPathConstant { REPOSITORY_API_PREFIX + "/create"; public static final String SSH_KEY_API_PREFIX = ALL_API_PREFIX + "/ssh"; - public static final String SSH_KEY_UPLOAD_SSH_KEY_API_PATH = - SSH_KEY_API_PREFIX + "/upload"; - public static final String SSH_KEY_UPDATE_SSH_KEY_API_PATH = - SSH_KEY_API_PREFIX + "/update"; - public static final String SSH_KEY_DELETE_SSH_KEY_API_PATH = - SSH_KEY_API_PREFIX + "/delete"; - public static final String SSH_KEY_PAGE_SSH_KEY_API_PATH = - SSH_KEY_API_PREFIX + "/page"; - + public static final String SSH_KEY_UPLOAD_SSH_KEY_API_PATH = SSH_KEY_API_PREFIX + "/upload"; + public static final String SSH_KEY_UPDATE_SSH_KEY_API_PATH = SSH_KEY_API_PREFIX + "/update"; + public static final String SSH_KEY_DELETE_SSH_KEY_API_PATH = SSH_KEY_API_PREFIX + "/delete"; + public static final String SSH_KEY_PAGE_SSH_KEY_API_PATH = SSH_KEY_API_PREFIX + "/page"; } diff --git a/src/main/java/edu/cmipt/gcs/constant/GitConstant.java b/src/main/java/edu/cmipt/gcs/constant/GitConstant.java index 409d238..049bc70 100644 --- a/src/main/java/edu/cmipt/gcs/constant/GitConstant.java +++ b/src/main/java/edu/cmipt/gcs/constant/GitConstant.java @@ -15,7 +15,8 @@ public class GitConstant { public static String GIT_SERVER_DOMAIN; - public static final String SSH_KEY_PREFIX = "no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty "; + public static final String SSH_KEY_PREFIX = + "no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty "; @Value("${git.user.name}") public void setGIT_USER_NAME(String gitUserName) { diff --git a/src/main/java/edu/cmipt/gcs/controller/SshKeyController.java b/src/main/java/edu/cmipt/gcs/controller/SshKeyController.java index 029ed0b..16db97a 100644 --- a/src/main/java/edu/cmipt/gcs/controller/SshKeyController.java +++ b/src/main/java/edu/cmipt/gcs/controller/SshKeyController.java @@ -1,5 +1,8 @@ package edu.cmipt.gcs.controller; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; + import edu.cmipt.gcs.constant.ApiPathConstant; import edu.cmipt.gcs.constant.HeaderParameter; import edu.cmipt.gcs.enumeration.ErrorCodeEnum; @@ -12,6 +15,7 @@ import edu.cmipt.gcs.util.JwtUtil; import edu.cmipt.gcs.validation.group.CreateGroup; import edu.cmipt.gcs.validation.group.UpdateGroup; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameters; @@ -22,9 +26,6 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; -import java.util.List; -import java.util.stream.Collectors; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; @@ -36,8 +37,8 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import java.util.List; +import java.util.stream.Collectors; @RestController @Tag(name = "SSH", description = "SSH APIs") @@ -55,7 +56,8 @@ public class SshKeyController { description = "Access token", required = true, in = ParameterIn.HEADER, - schema = @Schema(implementation = String.class))}) + schema = @Schema(implementation = String.class)) + }) @ApiResponses({ @ApiResponse(responseCode = "200", description = "SSH key uploaded successfully"), @ApiResponse( @@ -64,8 +66,9 @@ public class SshKeyController { content = @Content(schema = @Schema(implementation = ErrorVO.class))), @ApiResponse(responseCode = "500", description = "Internal server error") }) - public void uploadSshKey(@Validated(CreateGroup.class) @RequestBody SshKeyDTO sshKeyDTO, - @RequestHeader(HeaderParameter.ACCESS_TOKEN) String accessToken){ + public void uploadSshKey( + @Validated(CreateGroup.class) @RequestBody SshKeyDTO sshKeyDTO, + @RequestHeader(HeaderParameter.ACCESS_TOKEN) String accessToken) { if (!sshKeyService.save(new SshKeyPO(sshKeyDTO))) { throw new GenericException(ErrorCodeEnum.SSH_KEY_UPLOAD_FAILED, sshKeyDTO); } @@ -88,10 +91,12 @@ public void uploadSshKey(@Validated(CreateGroup.class) @RequestBody SshKeyDTO ss description = "SSH key ID", required = true, in = ParameterIn.QUERY, - schema = @Schema(implementation = Long.class))}) + schema = @Schema(implementation = Long.class)) + }) @ApiResponse(responseCode = "200", description = "SSH key deleted successfully") - public void deleteSshKey(@RequestHeader(HeaderParameter.ACCESS_TOKEN) String accessToken, - @RequestParam("id") Long id) { + public void deleteSshKey( + @RequestHeader(HeaderParameter.ACCESS_TOKEN) String accessToken, + @RequestParam("id") Long id) { var res = sshKeyService.getById(id); if (res == null) { throw new GenericException(ErrorCodeEnum.SSH_KEY_NOT_FOUND, id); @@ -115,20 +120,22 @@ public void deleteSshKey(@RequestHeader(HeaderParameter.ACCESS_TOKEN) String acc description = "Access token", required = true, in = ParameterIn.HEADER, - schema = @Schema(implementation = String.class))}) + schema = @Schema(implementation = String.class)) + }) @ApiResponses({ @ApiResponse(responseCode = "200", description = "SSH key updated successfully"), @ApiResponse( responseCode = "400", description = "SSH key update failed", - content = @Content(schema = @Schema(implementation = ErrorVO.class)))}) + content = @Content(schema = @Schema(implementation = ErrorVO.class))) + }) public ResponseEntity updateSshKey( - @Validated(UpdateGroup.class) @RequestBody SshKeyDTO sshKeyDTO - ) { + @Validated(UpdateGroup.class) @RequestBody SshKeyDTO sshKeyDTO) { if (!sshKeyService.updateById(new SshKeyPO(sshKeyDTO))) { throw new GenericException(ErrorCodeEnum.SSH_KEY_UPDATE_FAILED, sshKeyDTO); } - return ResponseEntity.ok().body(new SshKeyVO(sshKeyService.getById(Long.valueOf(sshKeyDTO.id())))); + return ResponseEntity.ok() + .body(new SshKeyVO(sshKeyService.getById(Long.valueOf(sshKeyDTO.id())))); } @GetMapping(ApiPathConstant.SSH_KEY_PAGE_SSH_KEY_API_PATH) @@ -162,12 +169,17 @@ public ResponseEntity updateSshKey( example = "10", required = true, in = ParameterIn.QUERY, - schema = @Schema(implementation = Integer.class))}) + schema = @Schema(implementation = Integer.class)) + }) @ApiResponse(responseCode = "200", description = "SSH key paged successfully") - public List pageSshKey(@RequestParam("id") Long userId, - @RequestParam("page") Integer page, @RequestParam("size") Integer size) { + public List pageSshKey( + @RequestParam("id") Long userId, + @RequestParam("page") Integer page, + @RequestParam("size") Integer size) { QueryWrapper wrapper = new QueryWrapper<>(); wrapper.eq("user_id", userId); - return sshKeyService.list(new Page<>(page, size), wrapper).stream().map(SshKeyVO::new).collect(Collectors.toList()); + return sshKeyService.list(new Page<>(page, size), wrapper).stream() + .map(SshKeyVO::new) + .collect(Collectors.toList()); } } diff --git a/src/main/java/edu/cmipt/gcs/filter/JwtFilter.java b/src/main/java/edu/cmipt/gcs/filter/JwtFilter.java index 5331ed9..7facd4c 100644 --- a/src/main/java/edu/cmipt/gcs/filter/JwtFilter.java +++ b/src/main/java/edu/cmipt/gcs/filter/JwtFilter.java @@ -157,15 +157,15 @@ private void authorize(HttpServletRequest request, String accessToken, String re } else if (request.getRequestURI() .equals(ApiPathConstant.USER_PAGE_USER_REPOSITORY_API_PATH)) { // pass - } else if (request.getRequestURI() - .equals(ApiPathConstant.USER_GET_USER_API_PATH)) { + } else if (request.getRequestURI().equals(ApiPathConstant.USER_GET_USER_API_PATH)) { // pass } else if (request.getRequestURI() .equals(ApiPathConstant.SSH_KEY_PAGE_SSH_KEY_API_PATH)) { String idInToken = JwtUtil.getId(accessToken); String idInParam = request.getParameter("id"); if (!idInToken.equals(idInParam)) { - logger.info("User[{}] tried to get SSH key of user[{}]", idInToken, idInParam); + logger.info( + "User[{}] tried to get SSH key of user[{}]", idInToken, idInParam); throw new GenericException(ErrorCodeEnum.ACCESS_DENIED); } } else { @@ -201,7 +201,10 @@ private void authorize(HttpServletRequest request, String accessToken, String re String idInToken = JwtUtil.getId(accessToken); String idInBody = getFromRequestBody(request, "userId"); if (!idInToken.equals(idInBody)) { - logger.info("User[{}] tried to upload SSH key of user[{}]", idInToken, idInBody); + logger.info( + "User[{}] tried to upload SSH key of user[{}]", + idInToken, + idInBody); throw new GenericException(ErrorCodeEnum.ACCESS_DENIED); } } else if (request.getRequestURI() @@ -209,7 +212,10 @@ private void authorize(HttpServletRequest request, String accessToken, String re String idInToken = JwtUtil.getId(accessToken); String idInBody = getFromRequestBody(request, "userId"); if (!idInToken.equals(idInBody)) { - logger.info("User[{}] tried to update SSH key of user[{}]", idInToken, idInBody); + logger.info( + "User[{}] tried to update SSH key of user[{}]", + idInToken, + idInBody); throw new GenericException(ErrorCodeEnum.ACCESS_DENIED); } } else { diff --git a/src/main/java/edu/cmipt/gcs/pojo/ssh/SshKeyDTO.java b/src/main/java/edu/cmipt/gcs/pojo/ssh/SshKeyDTO.java index bbfc5e9..07b4c5a 100644 --- a/src/main/java/edu/cmipt/gcs/pojo/ssh/SshKeyDTO.java +++ b/src/main/java/edu/cmipt/gcs/pojo/ssh/SshKeyDTO.java @@ -3,7 +3,9 @@ import edu.cmipt.gcs.constant.ValidationConstant; import edu.cmipt.gcs.validation.group.CreateGroup; import edu.cmipt.gcs.validation.group.UpdateGroup; + import io.swagger.v3.oas.annotations.media.Schema; + import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Null; @@ -11,38 +13,34 @@ @Schema(description = "SSH Key Data Transfer Object") public record SshKeyDTO( - @Schema(description = "SSH Key ID") - @Null(groups = CreateGroup.class, message = "SSHKEYDTO_ID_NULL {SshKeyDTO.id.Null}") - @NotNull( - groups = UpdateGroup.class, - message = "SSHKEYDTO_ID_NOTNULL {SshKeyDTO.id.NotNull}") - String id, - @Schema(description = "User ID") - @NotBlank( - groups = {CreateGroup.class, UpdateGroup.class}, - message = "SSHKEYDTO_USERID_NOTBLANK {SshKeyDTO.userId.NotBlank}") - String userId, - @Schema( - description = "Name", - example = "My SSH Key") - @NotBlank( - groups = {CreateGroup.class, UpdateGroup.class}, - message = "SSHKEYDTO_NAME_NOTBLANK {SshKeyDTO.name.NotBlank}") - @Size( - groups = {CreateGroup.class, UpdateGroup.class}, - min = ValidationConstant.MIN_SSH_KEY_NAME_LENGTH, - max = ValidationConstant.MAX_SSH_KEY_NAME_LENGTH, - message = "SSHKEYDTO_NAME_SIZE {SshKeyDTO.name.Size}") - String name, - @Schema( - description = "Public Key") - @NotBlank( - groups = CreateGroup.class, - message = "SSHKEYDTO_PUBLICKEY_NOTBLANK {SshKeyDTO.publicKey.NotBlank}") - @Size( - groups = {CreateGroup.class, UpdateGroup.class}, - min = ValidationConstant.MIN_SSH_KEY_PUBLICKEY_LENGTH, - max = ValidationConstant.MAX_SSH_KEY_PUBLICKEY_LENGTH, - message = "SSHKEYDTO_PUBLICKEY_SIZE {SshKeyDTO.publicKey.Size}") - String publicKey) { -} + @Schema(description = "SSH Key ID") + @Null(groups = CreateGroup.class, message = "SSHKEYDTO_ID_NULL {SshKeyDTO.id.Null}") + @NotNull( + groups = UpdateGroup.class, + message = "SSHKEYDTO_ID_NOTNULL {SshKeyDTO.id.NotNull}") + String id, + @Schema(description = "User ID") + @NotBlank( + groups = {CreateGroup.class, UpdateGroup.class}, + message = "SSHKEYDTO_USERID_NOTBLANK {SshKeyDTO.userId.NotBlank}") + String userId, + @Schema(description = "Name", example = "My SSH Key") + @NotBlank( + groups = {CreateGroup.class, UpdateGroup.class}, + message = "SSHKEYDTO_NAME_NOTBLANK {SshKeyDTO.name.NotBlank}") + @Size( + groups = {CreateGroup.class, UpdateGroup.class}, + min = ValidationConstant.MIN_SSH_KEY_NAME_LENGTH, + max = ValidationConstant.MAX_SSH_KEY_NAME_LENGTH, + message = "SSHKEYDTO_NAME_SIZE {SshKeyDTO.name.Size}") + String name, + @Schema(description = "Public Key") + @NotBlank( + groups = CreateGroup.class, + message = "SSHKEYDTO_PUBLICKEY_NOTBLANK {SshKeyDTO.publicKey.NotBlank}") + @Size( + groups = {CreateGroup.class, UpdateGroup.class}, + min = ValidationConstant.MIN_SSH_KEY_PUBLICKEY_LENGTH, + max = ValidationConstant.MAX_SSH_KEY_PUBLICKEY_LENGTH, + message = "SSHKEYDTO_PUBLICKEY_SIZE {SshKeyDTO.publicKey.Size}") + String publicKey) {} diff --git a/src/main/java/edu/cmipt/gcs/pojo/ssh/SshKeyPO.java b/src/main/java/edu/cmipt/gcs/pojo/ssh/SshKeyPO.java index 625a063..fb30763 100644 --- a/src/main/java/edu/cmipt/gcs/pojo/ssh/SshKeyPO.java +++ b/src/main/java/edu/cmipt/gcs/pojo/ssh/SshKeyPO.java @@ -1,13 +1,13 @@ package edu.cmipt.gcs.pojo.ssh; -import java.time.LocalDateTime; - import com.baomidou.mybatisplus.annotation.TableLogic; import com.baomidou.mybatisplus.annotation.TableName; import lombok.AllArgsConstructor; import lombok.Data; +import java.time.LocalDateTime; + @Data @AllArgsConstructor @TableName("t_ssh_key") diff --git a/src/main/java/edu/cmipt/gcs/pojo/ssh/SshKeyVO.java b/src/main/java/edu/cmipt/gcs/pojo/ssh/SshKeyVO.java index 101e24e..b227645 100644 --- a/src/main/java/edu/cmipt/gcs/pojo/ssh/SshKeyVO.java +++ b/src/main/java/edu/cmipt/gcs/pojo/ssh/SshKeyVO.java @@ -5,6 +5,10 @@ @Schema(description = "SSH Key Value Object") public record SshKeyVO(String id, String userId, String name, String publicKey) { public SshKeyVO(SshKeyPO sshKeyPO) { - this(sshKeyPO.getId().toString(), sshKeyPO.getUserId().toString(), sshKeyPO.getName(), sshKeyPO.getPublicKey()); + this( + sshKeyPO.getId().toString(), + sshKeyPO.getUserId().toString(), + sshKeyPO.getName(), + sshKeyPO.getPublicKey()); } } diff --git a/src/main/java/edu/cmipt/gcs/service/RepositoryServiceImpl.java b/src/main/java/edu/cmipt/gcs/service/RepositoryServiceImpl.java index 6ab2aa2..b643d31 100644 --- a/src/main/java/edu/cmipt/gcs/service/RepositoryServiceImpl.java +++ b/src/main/java/edu/cmipt/gcs/service/RepositoryServiceImpl.java @@ -28,7 +28,7 @@ public class RepositoryServiceImpl extends ServiceImpl Usually, the user will not create the same repository at the same time, so we don't + *

Usually, the user will not create the same repository at the same time, so we don't * consider the thread competition */ @Transactional @@ -42,16 +42,22 @@ public boolean save(RepositoryPO repositoryPO) { Paths.get( GitConstant.GIT_REPOSITORY_DIREDTORY, userMapper.selectById(repositoryPO.getUserId()).getUsername(), - repositoryPO.getRepositoryName() + GitConstant.GIT_REPOSITORY_SUFFIX) + repositoryPO.getRepositoryName() + + GitConstant.GIT_REPOSITORY_SUFFIX) .toString(); // check if the repositorySavePath has been created, if so, remove it // this may occur, if the last creation failed - if (Files.exists(Paths.get(repositorySavePath))){ + if (Files.exists(Paths.get(repositorySavePath))) { logger.info("Repository save path exists, try to remove it"); try { ProcessBuilder dirRemover = new ProcessBuilder( - "sudo", "-u", GitConstant.GIT_USER_NAME, "rm", "-rf", repositorySavePath); + "sudo", + "-u", + GitConstant.GIT_USER_NAME, + "rm", + "-rf", + repositorySavePath); Process process = dirRemover.start(); if (process.waitFor() != 0) { throw new GenericException( @@ -67,7 +73,13 @@ public boolean save(RepositoryPO repositoryPO) { try { ProcessBuilder repositoryInitializer = new ProcessBuilder( - "sudo", "-u", GitConstant.GIT_USER_NAME, "git", "init", "--bare", repositorySavePath); + "sudo", + "-u", + GitConstant.GIT_USER_NAME, + "git", + "init", + "--bare", + repositorySavePath); Process process = repositoryInitializer.start(); if (process.waitFor() != 0) { throw new GenericException( diff --git a/src/main/java/edu/cmipt/gcs/service/SshKeyService.java b/src/main/java/edu/cmipt/gcs/service/SshKeyService.java index 7ce3cb9..ec1366f 100644 --- a/src/main/java/edu/cmipt/gcs/service/SshKeyService.java +++ b/src/main/java/edu/cmipt/gcs/service/SshKeyService.java @@ -4,5 +4,4 @@ import edu.cmipt.gcs.pojo.ssh.SshKeyPO; - public interface SshKeyService extends IService {} diff --git a/src/main/java/edu/cmipt/gcs/service/SshKeyServiceImpl.java b/src/main/java/edu/cmipt/gcs/service/SshKeyServiceImpl.java index 12b7c80..30a90dd 100644 --- a/src/main/java/edu/cmipt/gcs/service/SshKeyServiceImpl.java +++ b/src/main/java/edu/cmipt/gcs/service/SshKeyServiceImpl.java @@ -1,13 +1,5 @@ package edu.cmipt.gcs.service; -import java.io.OutputStream; -import java.io.Serializable; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import edu.cmipt.gcs.constant.GitConstant; @@ -16,8 +8,17 @@ import edu.cmipt.gcs.exception.GenericException; import edu.cmipt.gcs.pojo.ssh.SshKeyPO; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.OutputStream; +import java.io.Serializable; + @Service -public class SshKeyServiceImpl extends ServiceImpl implements SshKeyService { +public class SshKeyServiceImpl extends ServiceImpl + implements SshKeyService { private static final Logger logger = LoggerFactory.getLogger(RepositoryServiceImpl.class); @Transactional @@ -53,7 +54,9 @@ public boolean updateById(SshKeyPO sshKeyPO) { return false; } // no need to update file, we just return true - if (sshKeyPO.getPublicKey() == null || originSshKey.equals(sshKeyPO.getPublicKey())) { return true; } + if (sshKeyPO.getPublicKey() == null || originSshKey.equals(sshKeyPO.getPublicKey())) { + return true; + } // remove the origin ssh key and save the new ssh key removeSshKeyFromAuthorizedKeys(originSshKey); saveSshKeyToAuthorizedKeys(sshKeyPO.getPublicKey()); @@ -62,8 +65,14 @@ public boolean updateById(SshKeyPO sshKeyPO) { private void saveSshKeyToAuthorizedKeys(String sshKey) { try { - ProcessBuilder sshKeySaver = new ProcessBuilder("sudo", "-u", GitConstant.GIT_USER_NAME, - "tee", "-a", GitConstant.GIT_HOME_DIRECTORY + "/.ssh/authorized_keys"); + ProcessBuilder sshKeySaver = + new ProcessBuilder( + "sudo", + "-u", + GitConstant.GIT_USER_NAME, + "tee", + "-a", + GitConstant.GIT_HOME_DIRECTORY + "/.ssh/authorized_keys"); // for singleton, we can use synchronized(this) to lock the object synchronized (this) { Process process = sshKeySaver.start(); @@ -73,7 +82,9 @@ private void saveSshKeyToAuthorizedKeys(String sshKey) { } if (process.waitFor() != 0) { logger.error("Failed to write SSH key to authorized_keys file"); - throw new GenericException(ErrorCodeEnum.SSH_KEY_UPLOAD_FAILED, process.errorReader().lines().toList().toString()); + throw new GenericException( + ErrorCodeEnum.SSH_KEY_UPLOAD_FAILED, + process.errorReader().lines().toList().toString()); } } } catch (Exception e) { @@ -84,14 +95,22 @@ private void saveSshKeyToAuthorizedKeys(String sshKey) { private void removeSshKeyFromAuthorizedKeys(String sshKey) { try { - ProcessBuilder sshKeyRemover = new ProcessBuilder("sudo", "-u", GitConstant.GIT_USER_NAME, - "sed", "-i", "/^" + GitConstant.SSH_KEY_PREFIX + sshKey + "$/d", - GitConstant.GIT_HOME_DIRECTORY + "/.ssh/authorized_keys"); + ProcessBuilder sshKeyRemover = + new ProcessBuilder( + "sudo", + "-u", + GitConstant.GIT_USER_NAME, + "sed", + "-i", + "/^" + GitConstant.SSH_KEY_PREFIX + sshKey + "$/d", + GitConstant.GIT_HOME_DIRECTORY + "/.ssh/authorized_keys"); synchronized (this) { Process process = sshKeyRemover.start(); if (process.waitFor() != 0) { logger.error("Failed to remove SSH key from authorized_keys"); - throw new GenericException(ErrorCodeEnum.SSH_KEY_DELETE_FAILED, process.errorReader().lines().toList().toString()); + throw new GenericException( + ErrorCodeEnum.SSH_KEY_DELETE_FAILED, + process.errorReader().lines().toList().toString()); } } } catch (Exception e) { diff --git a/src/test/java/edu/cmipt/gcs/controller/SshKeyControllerTest.java b/src/test/java/edu/cmipt/gcs/controller/SshKeyControllerTest.java index 2c15f52..85bf8bb 100644 --- a/src/test/java/edu/cmipt/gcs/controller/SshKeyControllerTest.java +++ b/src/test/java/edu/cmipt/gcs/controller/SshKeyControllerTest.java @@ -38,20 +38,19 @@ public void testUploadSshKeyValid() throws Exception { for (int i = 0; i < TestConstant.SSH_KEY_SIZE; i++) { String name = "My SSH Key " + i; String publicKey = "This is my public key " + i; - mockMvc - .perform( + mockMvc.perform( post(ApiPathConstant.SSH_KEY_UPLOAD_SSH_KEY_API_PATH) .header(HeaderParameter.ACCESS_TOKEN, TestConstant.ACCESS_TOKEN) .contentType(MediaType.APPLICATION_JSON) - .content( - """ - { - "name": "%s", - "userId": "%s", - "publicKey": "%s" - } - """.formatted(name, TestConstant.ID, publicKey) - )) + .content( + """ + { + "name": "%s", + "userId": "%s", + "publicKey": "%s" + } + """ + .formatted(name, TestConstant.ID, publicKey))) .andExpect(status().isOk()); } } @@ -59,17 +58,28 @@ public void testUploadSshKeyValid() throws Exception { @Test @Order(Ordered.HIGHEST_PRECEDENCE + 1) public void testPageSshKeyValid() throws Exception { - var response = mockMvc - .perform( - get(ApiPathConstant.SSH_KEY_PAGE_SSH_KEY_API_PATH) - .header(HeaderParameter.ACCESS_TOKEN, TestConstant.ACCESS_TOKEN) - .param("id", TestConstant.ID) - .param("page", "1") - .param("size", TestConstant.SSH_KEY_SIZE.toString())) - .andExpectAll(status().isOk(), - jsonPath("$").isArray(), - jsonPath("$.length()").value(TestConstant.SSH_KEY_SIZE)).andReturn().getResponse(); - Matcher matcher = Pattern.compile("id=(\\d+)").matcher(JsonParserFactory.getJsonParser().parseList(response.getContentAsString()).get(0).toString()); + var response = + mockMvc.perform( + get(ApiPathConstant.SSH_KEY_PAGE_SSH_KEY_API_PATH) + .header( + HeaderParameter.ACCESS_TOKEN, + TestConstant.ACCESS_TOKEN) + .param("id", TestConstant.ID) + .param("page", "1") + .param("size", TestConstant.SSH_KEY_SIZE.toString())) + .andExpectAll( + status().isOk(), + jsonPath("$").isArray(), + jsonPath("$.length()").value(TestConstant.SSH_KEY_SIZE)) + .andReturn() + .getResponse(); + Matcher matcher = + Pattern.compile("id=(\\d+)") + .matcher( + JsonParserFactory.getJsonParser() + .parseList(response.getContentAsString()) + .get(0) + .toString()); matcher.find(); TestConstant.SSH_KEY_ID = matcher.group(1); } @@ -77,8 +87,7 @@ public void testPageSshKeyValid() throws Exception { @Test @Order(Ordered.HIGHEST_PRECEDENCE + 2) public void testUpdateSshKeyValid() throws Exception { - mockMvc - .perform( + mockMvc.perform( post(ApiPathConstant.SSH_KEY_UPDATE_SSH_KEY_API_PATH) .header(HeaderParameter.ACCESS_TOKEN, TestConstant.ACCESS_TOKEN) .contentType(MediaType.APPLICATION_JSON) @@ -90,14 +99,15 @@ public void testUpdateSshKeyValid() throws Exception { "userId": "%s", "publicKey": "This is my public key updated" } - """.formatted(TestConstant.SSH_KEY_ID, TestConstant.ID))) + """ + .formatted( + TestConstant.SSH_KEY_ID, TestConstant.ID))) .andExpectAll( - status().isOk(), - jsonPath("$.id", is(TestConstant.SSH_KEY_ID)), - jsonPath("$.userId", is(TestConstant.ID)), - jsonPath("$.name", is("My SSH Key Updated")), - jsonPath("$.publicKey", is("This is my public key updated")) - ); + status().isOk(), + jsonPath("$.id", is(TestConstant.SSH_KEY_ID)), + jsonPath("$.userId", is(TestConstant.ID)), + jsonPath("$.name", is("My SSH Key Updated")), + jsonPath("$.publicKey", is("This is my public key updated"))); } /** @@ -110,8 +120,7 @@ public void testUpdateSshKeyValid() throws Exception { @Test @Order(Ordered.HIGHEST_PRECEDENCE + 3) public void testDeleteSshKeyValid() throws Exception { - mockMvc - .perform( + mockMvc.perform( delete(ApiPathConstant.SSH_KEY_DELETE_SSH_KEY_API_PATH) .header(HeaderParameter.ACCESS_TOKEN, TestConstant.ACCESS_TOKEN) .param("id", TestConstant.SSH_KEY_ID))