diff --git a/backend/src/main/java/com/vaessl/app/config/CorsConfig.java b/backend/src/main/java/com/vaessl/app/config/CorsConfig.java index baa8836..f9ce4f8 100644 --- a/backend/src/main/java/com/vaessl/app/config/CorsConfig.java +++ b/backend/src/main/java/com/vaessl/app/config/CorsConfig.java @@ -13,10 +13,8 @@ public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { - registry.addMapping("/**") - .allowedOrigins(allowedOrigins) + registry.addMapping("/**").allowedOrigins(allowedOrigins) .allowedMethods("GET", "POST", "DELETE", "OPTIONS") - .allowedHeaders("Content-Type", "Accept") - .allowCredentials(true); + .allowedHeaders("Content-Type", "Accept").allowCredentials(true); } } diff --git a/backend/src/main/java/com/vaessl/app/connection/AuthResponse.java b/backend/src/main/java/com/vaessl/app/connection/AuthResponse.java index 992c23a..0bdda64 100644 --- a/backend/src/main/java/com/vaessl/app/connection/AuthResponse.java +++ b/backend/src/main/java/com/vaessl/app/connection/AuthResponse.java @@ -2,4 +2,5 @@ package com.vaessl.app.connection; import java.time.Instant; -public record AuthResponse(String serviceType, Instant expiresAt) {} +public record AuthResponse(String serviceType, Instant expiresAt) { +} diff --git a/backend/src/main/java/com/vaessl/app/connection/ConnectionController.java b/backend/src/main/java/com/vaessl/app/connection/ConnectionController.java index 09f4bd9..9222b63 100644 --- a/backend/src/main/java/com/vaessl/app/connection/ConnectionController.java +++ b/backend/src/main/java/com/vaessl/app/connection/ConnectionController.java @@ -28,8 +28,7 @@ public class ConnectionController { private final ConnectionService connectionService; @PostMapping("/login") - public ResponseEntity login( - @Valid @RequestBody ConnectionRequest request, + public ResponseEntity login(@Valid @RequestBody ConnectionRequest request, HttpServletRequest httpReq) { LoginResult result = connectionService.login(request); @@ -53,21 +52,21 @@ public class ConnectionController { } List statuses = new ArrayList<>(); - Collections.list(session.getAttributeNames()).stream() - .filter(k -> k.endsWith(SUFFIX)) + Collections.list(session.getAttributeNames()).stream().filter(k -> k.endsWith(SUFFIX)) .forEach(k -> { String serviceType = k.replace(SUFFIX, ""); Long id = (Long) session.getAttribute(k); - ConnectionStatusResponse status = connectionService.getConnectionStatus(serviceType, id); - if (status != null) statuses.add(status); + ConnectionStatusResponse status = + connectionService.getConnectionStatus(serviceType, id); + if (status != null) + statuses.add(status); }); return ResponseEntity.ok(statuses); } @DeleteMapping("/connections/{serviceType}") - public ResponseEntity logout( - @PathVariable("serviceType") String serviceType, + public ResponseEntity logout(@PathVariable("serviceType") String serviceType, HttpServletRequest httpReq) { HttpSession session = httpReq.getSession(false); diff --git a/backend/src/main/java/com/vaessl/app/connection/ConnectionEntity.java b/backend/src/main/java/com/vaessl/app/connection/ConnectionEntity.java index 96b769f..586921a 100644 --- a/backend/src/main/java/com/vaessl/app/connection/ConnectionEntity.java +++ b/backend/src/main/java/com/vaessl/app/connection/ConnectionEntity.java @@ -14,7 +14,8 @@ import lombok.NoArgsConstructor; import lombok.Setter; @Entity -@Table(name = "connections", uniqueConstraints = { @UniqueConstraint(columnNames = { "appUrl", "username" }) }) +@Table(name = "connections", + uniqueConstraints = {@UniqueConstraint(columnNames = {"appUrl", "username"})}) @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "service_type") @Getter diff --git a/backend/src/main/java/com/vaessl/app/connection/ConnectionRequest.java b/backend/src/main/java/com/vaessl/app/connection/ConnectionRequest.java index 3df55d7..9edfa5b 100644 --- a/backend/src/main/java/com/vaessl/app/connection/ConnectionRequest.java +++ b/backend/src/main/java/com/vaessl/app/connection/ConnectionRequest.java @@ -4,12 +4,9 @@ import com.fasterxml.jackson.annotation.JsonProperty; import jakarta.validation.constraints.NotBlank; -public record ConnectionRequest( - @NotBlank(message = "App URL is mandatory") String appUrl, +public record ConnectionRequest(@NotBlank(message = "App URL is mandatory") String appUrl, @NotBlank(message = "Service type is mandatory") String serviceType, - String username, - String password, - String apiKey, + String username, String password, String apiKey, @JsonProperty(defaultValue = "false") Boolean stayLoggedIn) { public ConnectionRequest { @@ -18,8 +15,8 @@ public record ConnectionRequest( } } - public ConnectionRequest(String appUrl, String serviceType, String username, String password, - Boolean stayLoggedIn) { + public ConnectionRequest(String appUrl, String serviceType, String username, + String password, Boolean stayLoggedIn) { this(appUrl, serviceType, username, password, null, stayLoggedIn); } } diff --git a/backend/src/main/java/com/vaessl/app/connection/ConnectionResponse.java b/backend/src/main/java/com/vaessl/app/connection/ConnectionResponse.java index 9ba9b87..41b278c 100644 --- a/backend/src/main/java/com/vaessl/app/connection/ConnectionResponse.java +++ b/backend/src/main/java/com/vaessl/app/connection/ConnectionResponse.java @@ -3,10 +3,11 @@ package com.vaessl.app.connection; import java.time.Instant; import java.util.Map; -public record ConnectionResponse(String token, Instant expiresAt, Map extraResponseData) { - +public record ConnectionResponse(String token, Instant expiresAt, + Map extraResponseData) { + public String getExtraVar(String key) { - if(extraResponseData == null) { + if (extraResponseData == null) { return null; } else { Object value = extraResponseData.get(key); diff --git a/backend/src/main/java/com/vaessl/app/connection/ConnectionService.java b/backend/src/main/java/com/vaessl/app/connection/ConnectionService.java index 864f366..dab76b2 100644 --- a/backend/src/main/java/com/vaessl/app/connection/ConnectionService.java +++ b/backend/src/main/java/com/vaessl/app/connection/ConnectionService.java @@ -50,13 +50,14 @@ public class ConnectionService { public ConnectionStatusResponse getConnectionStatus(String serviceType, Long connectionId) { ConnectionEntity entity = cRepository.findById(connectionId).orElse(null); - if (entity == null) return null; + if (entity == null) + return null; ConnectionProvider provider = providerRegistry.get(serviceType); Instant expiresAt = (provider != null) ? provider.getTokenExpiry(entity) : null; boolean connected = expiresAt == null || expiresAt.isAfter(Instant.now()); - return new ConnectionStatusResponse(serviceType, entity.getAppUrl(), - entity.getUsername(), expiresAt, connected); + return new ConnectionStatusResponse(serviceType, entity.getAppUrl(), entity.getUsername(), + expiresAt, connected); } } diff --git a/backend/src/main/java/com/vaessl/app/connection/ConnectionStatusResponse.java b/backend/src/main/java/com/vaessl/app/connection/ConnectionStatusResponse.java index 1d1fc62..be5ee04 100644 --- a/backend/src/main/java/com/vaessl/app/connection/ConnectionStatusResponse.java +++ b/backend/src/main/java/com/vaessl/app/connection/ConnectionStatusResponse.java @@ -2,9 +2,6 @@ package com.vaessl.app.connection; import java.time.Instant; -public record ConnectionStatusResponse( - String serviceType, - String appUrl, - String username, - Instant expiresAt, - boolean connected) {} +public record ConnectionStatusResponse(String serviceType, String appUrl, String username, + Instant expiresAt, boolean connected) { +} diff --git a/backend/src/main/java/com/vaessl/app/connection/Endpoint.java b/backend/src/main/java/com/vaessl/app/connection/Endpoint.java index d8b7426..0960c26 100644 --- a/backend/src/main/java/com/vaessl/app/connection/Endpoint.java +++ b/backend/src/main/java/com/vaessl/app/connection/Endpoint.java @@ -1,9 +1,7 @@ package com.vaessl.app.connection; public enum Endpoint { - HOMEBOX_LOGIN("/api/v1/users/login"), - LOGIN("/login"), - CONNECTION_STATUS("/connections/status"); + HOMEBOX_LOGIN("/api/v1/users/login"), LOGIN("/login"), CONNECTION_STATUS("/connections/status"); private final String value; diff --git a/backend/src/main/java/com/vaessl/app/connection/LoginResult.java b/backend/src/main/java/com/vaessl/app/connection/LoginResult.java index 61e7b43..49349ec 100644 --- a/backend/src/main/java/com/vaessl/app/connection/LoginResult.java +++ b/backend/src/main/java/com/vaessl/app/connection/LoginResult.java @@ -2,4 +2,5 @@ package com.vaessl.app.connection; import java.time.Instant; -public record LoginResult(Long connectionId, Instant expiresAt) {} +public record LoginResult(Long connectionId, Instant expiresAt) { +} diff --git a/backend/src/main/java/com/vaessl/app/connection/ServiceType.java b/backend/src/main/java/com/vaessl/app/connection/ServiceType.java index d579690..4c3fc5f 100644 --- a/backend/src/main/java/com/vaessl/app/connection/ServiceType.java +++ b/backend/src/main/java/com/vaessl/app/connection/ServiceType.java @@ -8,7 +8,7 @@ public enum ServiceType { private final String value; - private ServiceType(String value){ + private ServiceType(String value) { this.value = value; } } diff --git a/backend/src/main/java/com/vaessl/app/exception/ErrorMessage.java b/backend/src/main/java/com/vaessl/app/exception/ErrorMessage.java index ae14081..17b27ff 100644 --- a/backend/src/main/java/com/vaessl/app/exception/ErrorMessage.java +++ b/backend/src/main/java/com/vaessl/app/exception/ErrorMessage.java @@ -5,11 +5,13 @@ import org.springframework.http.HttpStatus; import com.fasterxml.jackson.annotation.JsonValue; public enum ErrorMessage { - BAD_REQUEST_EMPTY_FIELDS(HttpStatus.BAD_REQUEST, "Fields must not be empty."), UNAUTHORIZED_WRONG_LOGIN( - HttpStatus.UNAUTHORIZED, "Invalid username or password."), SERVICE_UNAVAILABLE_UNREACHABLE_URL( - HttpStatus.SERVICE_UNAVAILABLE, "The target URL is unreachable."), SERVER_ERROR_GENERAL( - "The external app returned a server error: "), WRONG_SERVICE_TYPE(HttpStatus.NOT_FOUND, - "No such service type."); + BAD_REQUEST_EMPTY_FIELDS(HttpStatus.BAD_REQUEST, + "Fields must not be empty."), UNAUTHORIZED_WRONG_LOGIN(HttpStatus.UNAUTHORIZED, + "Invalid username or password."), SERVICE_UNAVAILABLE_UNREACHABLE_URL( + HttpStatus.SERVICE_UNAVAILABLE, + "The target URL is unreachable."), SERVER_ERROR_GENERAL( + "The external app returned a server error: "), WRONG_SERVICE_TYPE( + HttpStatus.NOT_FOUND, "No such service type."); private final HttpStatus status; private final String message; diff --git a/backend/src/main/java/com/vaessl/app/exception/GlobalExceptionHandler.java b/backend/src/main/java/com/vaessl/app/exception/GlobalExceptionHandler.java index 08994c0..db29162 100644 --- a/backend/src/main/java/com/vaessl/app/exception/GlobalExceptionHandler.java +++ b/backend/src/main/java/com/vaessl/app/exception/GlobalExceptionHandler.java @@ -19,8 +19,8 @@ public class GlobalExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException.class) public ProblemDetail handleEmptyCredentialInput(MethodArgumentNotValidException e) { - String defaultMessages = e.getBindingResult().getFieldErrors().stream().map(FieldError::getDefaultMessage) - .collect(Collectors.joining(", ")); + String defaultMessages = e.getBindingResult().getFieldErrors().stream() + .map(FieldError::getDefaultMessage).collect(Collectors.joining(", ")); return ProblemDetail.forStatusAndDetail(BAD_REQUEST_EMPTY_FIELDS.getStatus(), BAD_REQUEST_EMPTY_FIELDS.getMessage() + " [" + defaultMessages + "]"); @@ -43,14 +43,14 @@ public class GlobalExceptionHandler { @ExceptionHandler(HttpServerErrorException.class) public ProblemDetail handleTimeoutOrNotFound(HttpServerErrorException e) { - return ProblemDetail - .forStatusAndDetail(e.getStatusCode(), - SERVER_ERROR_GENERAL.getMessage() + e.getStatusText()); + return ProblemDetail.forStatusAndDetail(e.getStatusCode(), + SERVER_ERROR_GENERAL.getMessage() + e.getStatusText()); } @ExceptionHandler(WrongServiceTypeException.class) public ProblemDetail handleWrongServiceType(WrongServiceTypeException e) { - return ProblemDetail.forStatusAndDetail(WRONG_SERVICE_TYPE.getStatus(), WRONG_SERVICE_TYPE.getMessage()); + return ProblemDetail.forStatusAndDetail(WRONG_SERVICE_TYPE.getStatus(), + WRONG_SERVICE_TYPE.getMessage()); } @ExceptionHandler(EmptyCredentialsException.class) diff --git a/backend/src/test/java/com/vaessl/app/ApplicationTests.java b/backend/src/test/java/com/vaessl/app/ApplicationTests.java index b2954e9..40849b1 100644 --- a/backend/src/test/java/com/vaessl/app/ApplicationTests.java +++ b/backend/src/test/java/com/vaessl/app/ApplicationTests.java @@ -20,8 +20,7 @@ class ApplicationTests { private DataSource dataSource; @Test - void contextLoads() { - } + void contextLoads() {} @Test void connectionToTestDbWorks() throws SQLException { diff --git a/backend/src/test/java/com/vaessl/app/connection/ConnectionControllerTest.java b/backend/src/test/java/com/vaessl/app/connection/ConnectionControllerTest.java index 906fd42..30331e9 100644 --- a/backend/src/test/java/com/vaessl/app/connection/ConnectionControllerTest.java +++ b/backend/src/test/java/com/vaessl/app/connection/ConnectionControllerTest.java @@ -24,134 +24,131 @@ import org.springframework.test.web.servlet.MvcResult; @WireMockTest class ConnectionControllerTest { - @Autowired - MockMvc mockMvc; + @Autowired + MockMvc mockMvc; - private static final String TEST_USER = "admin"; - private static final String TEST_PASS = "pw"; - private static final String LOGIN_PATH = LOGIN.getValue(); - private static final String STATUS_PATH = CONNECTION_STATUS.getValue(); - private static final String LOGOUT_PATH = "/connections/HOMEBOX"; + private static final String TEST_USER = "admin"; + private static final String TEST_PASS = "pw"; + private static final String LOGIN_PATH = LOGIN.getValue(); + private static final String STATUS_PATH = CONNECTION_STATUS.getValue(); + private static final String LOGOUT_PATH = "/connections/HOMEBOX"; - private static final String VALID_HOMEBOX_RESPONSE = """ - { - "token": "fake-jwt-token", - "attachmentToken": "fake-attach", - "expiresAt": "2099-01-01T00:00:00Z" - } - """; + private static final String VALID_HOMEBOX_RESPONSE = """ + { + "token": "fake-jwt-token", + "attachmentToken": "fake-attach", + "expiresAt": "2099-01-01T00:00:00Z" + } + """; - private static final String EXPIRED_HOMEBOX_RESPONSE = """ - { - "token": "expired-token", - "attachmentToken": "fake-attach", - "expiresAt": "2000-01-01T00:00:00Z" - } - """; + private static final String EXPIRED_HOMEBOX_RESPONSE = """ + { + "token": "expired-token", + "attachmentToken": "fake-attach", + "expiresAt": "2000-01-01T00:00:00Z" + } + """; - @Test - void shouldReturnEmptyListWhenNoActiveSession() throws Exception { - mockMvc.perform(get(STATUS_PATH)) - .andExpect(status().isOk()) - .andExpect(content().json("[]")); - } + @Test + void shouldReturnEmptyListWhenNoActiveSession() throws Exception { + mockMvc.perform(get(STATUS_PATH)).andExpect(status().isOk()) + .andExpect(content().json("[]")); + } - @Test - void shouldReturnConnectionStatusWithConnectedTrueAfterLogin(WireMockRuntimeInfo wm) throws Exception { - WireMock.stubFor(WireMock.post(HOMEBOX_LOGIN.getValue()).willReturn(WireMock.okJson(VALID_HOMEBOX_RESPONSE))); + @Test + void shouldReturnConnectionStatusWithConnectedTrueAfterLogin(WireMockRuntimeInfo wm) + throws Exception { + WireMock.stubFor(WireMock.post(HOMEBOX_LOGIN.getValue()) + .willReturn(WireMock.okJson(VALID_HOMEBOX_RESPONSE))); - MvcResult loginResult = mockMvc.perform(post(LOGIN_PATH) - .contentType(MediaType.APPLICATION_JSON) - .content(connectionRequestBody(wm))) - .andExpect(status().isOk()) - .andReturn(); + MvcResult loginResult = mockMvc + .perform(post(LOGIN_PATH).contentType(MediaType.APPLICATION_JSON) + .content(connectionRequestBody(wm))) + .andExpect(status().isOk()).andReturn(); - Cookie sessionCookie = loginResult.getResponse().getCookie("SESSION"); + Cookie sessionCookie = loginResult.getResponse().getCookie("SESSION"); - mockMvc.perform(get(STATUS_PATH).cookie(sessionCookie)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.length()").value(1)) - .andExpect(jsonPath("$[0].serviceType").value(HOMEBOX.getValue())) - .andExpect(jsonPath("$[0].username").value(TEST_USER)) - .andExpect(jsonPath("$[0].appUrl").value(wm.getHttpBaseUrl())) - .andExpect(jsonPath("$[0].connected").value(true)); - } + mockMvc.perform(get(STATUS_PATH).cookie(sessionCookie)).andExpect(status().isOk()) + .andExpect(jsonPath("$.length()").value(1)) + .andExpect(jsonPath("$[0].serviceType").value(HOMEBOX.getValue())) + .andExpect(jsonPath("$[0].username").value(TEST_USER)) + .andExpect(jsonPath("$[0].appUrl").value(wm.getHttpBaseUrl())) + .andExpect(jsonPath("$[0].connected").value(true)); + } - @Test - void shouldReturnConnectedFalseWhenStoredTokenIsExpired(WireMockRuntimeInfo wm) throws Exception { - WireMock.stubFor(WireMock.post(HOMEBOX_LOGIN.getValue()).willReturn(WireMock.okJson(EXPIRED_HOMEBOX_RESPONSE))); + @Test + void shouldReturnConnectedFalseWhenStoredTokenIsExpired(WireMockRuntimeInfo wm) + throws Exception { + WireMock.stubFor(WireMock.post(HOMEBOX_LOGIN.getValue()) + .willReturn(WireMock.okJson(EXPIRED_HOMEBOX_RESPONSE))); - MvcResult loginResult = mockMvc.perform(post(LOGIN_PATH) - .contentType(MediaType.APPLICATION_JSON) - .content(connectionRequestBody(wm))) - .andExpect(status().isOk()) - .andReturn(); + MvcResult loginResult = mockMvc + .perform(post(LOGIN_PATH).contentType(MediaType.APPLICATION_JSON) + .content(connectionRequestBody(wm))) + .andExpect(status().isOk()).andReturn(); - Cookie sessionCookie = loginResult.getResponse().getCookie("SESSION"); + Cookie sessionCookie = loginResult.getResponse().getCookie("SESSION"); - mockMvc.perform(get(STATUS_PATH).cookie(sessionCookie)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$[0].serviceType").value(HOMEBOX.getValue())) - .andExpect(jsonPath("$[0].connected").value(false)) - .andExpect(jsonPath("$[0].expiresAt").value("2000-01-01T00:00:00Z")); - } + mockMvc.perform(get(STATUS_PATH).cookie(sessionCookie)).andExpect(status().isOk()) + .andExpect(jsonPath("$[0].serviceType").value(HOMEBOX.getValue())) + .andExpect(jsonPath("$[0].connected").value(false)) + .andExpect(jsonPath("$[0].expiresAt") + .value("2000-01-01T00:00:00Z")); + } - @Test - void shouldReturn204NoContentOnLogout(WireMockRuntimeInfo wm) throws Exception { - WireMock.stubFor(WireMock.post(HOMEBOX_LOGIN.getValue()).willReturn(WireMock.okJson(VALID_HOMEBOX_RESPONSE))); + @Test + void shouldReturn204NoContentOnLogout(WireMockRuntimeInfo wm) throws Exception { + WireMock.stubFor(WireMock.post(HOMEBOX_LOGIN.getValue()) + .willReturn(WireMock.okJson(VALID_HOMEBOX_RESPONSE))); - MvcResult loginResult = mockMvc.perform(post(LOGIN_PATH) - .contentType(MediaType.APPLICATION_JSON) - .content(connectionRequestBody(wm))) - .andExpect(status().isOk()) - .andReturn(); + MvcResult loginResult = mockMvc + .perform(post(LOGIN_PATH).contentType(MediaType.APPLICATION_JSON) + .content(connectionRequestBody(wm))) + .andExpect(status().isOk()).andReturn(); - Cookie sessionCookie = loginResult.getResponse().getCookie("SESSION"); + Cookie sessionCookie = loginResult.getResponse().getCookie("SESSION"); - mockMvc.perform(delete(LOGOUT_PATH).cookie(sessionCookie)) - .andExpect(status().isNoContent()); - } + mockMvc.perform(delete(LOGOUT_PATH).cookie(sessionCookie)) + .andExpect(status().isNoContent()); + } - @Test - void shouldReturnEmptyStatusListAfterLogout(WireMockRuntimeInfo wm) throws Exception { - WireMock.stubFor(WireMock.post(HOMEBOX_LOGIN.getValue()).willReturn(WireMock.okJson(VALID_HOMEBOX_RESPONSE))); + @Test + void shouldReturnEmptyStatusListAfterLogout(WireMockRuntimeInfo wm) throws Exception { + WireMock.stubFor(WireMock.post(HOMEBOX_LOGIN.getValue()) + .willReturn(WireMock.okJson(VALID_HOMEBOX_RESPONSE))); - MvcResult loginResult = mockMvc.perform(post(LOGIN_PATH) - .contentType(MediaType.APPLICATION_JSON) - .content(connectionRequestBody(wm))) - .andExpect(status().isOk()) - .andReturn(); + MvcResult loginResult = mockMvc + .perform(post(LOGIN_PATH).contentType(MediaType.APPLICATION_JSON) + .content(connectionRequestBody(wm))) + .andExpect(status().isOk()).andReturn(); - Cookie sessionCookie = loginResult.getResponse().getCookie("SESSION"); + Cookie sessionCookie = loginResult.getResponse().getCookie("SESSION"); - // Verify connected before logout - mockMvc.perform(get(STATUS_PATH).cookie(sessionCookie)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.length()").value(1)); + // Verify connected before logout + mockMvc.perform(get(STATUS_PATH).cookie(sessionCookie)).andExpect(status().isOk()) + .andExpect(jsonPath("$.length()").value(1)); - mockMvc.perform(delete(LOGOUT_PATH).cookie(sessionCookie)) - .andExpect(status().isNoContent()); + mockMvc.perform(delete(LOGOUT_PATH).cookie(sessionCookie)) + .andExpect(status().isNoContent()); - // A new request (no session cookie, as in a fresh browser) returns no connections - mockMvc.perform(get(STATUS_PATH)) - .andExpect(status().isOk()) - .andExpect(content().json("[]")); - } + // A new request (no session cookie, as in a fresh browser) returns no connections + mockMvc.perform(get(STATUS_PATH)).andExpect(status().isOk()) + .andExpect(content().json("[]")); + } - @Test - void shouldReturn204WhenLogoutCalledWithNoActiveSession() throws Exception { - mockMvc.perform(delete(LOGOUT_PATH)) - .andExpect(status().isNoContent()); - } + @Test + void shouldReturn204WhenLogoutCalledWithNoActiveSession() throws Exception { + mockMvc.perform(delete(LOGOUT_PATH)).andExpect(status().isNoContent()); + } - private String connectionRequestBody(WireMockRuntimeInfo wm) { - return """ - { - "appUrl": "%s", - "serviceType": "HOMEBOX", - "username": "%s", - "password": "%s" - } - """.formatted(wm.getHttpBaseUrl(), TEST_USER, TEST_PASS); - } + private String connectionRequestBody(WireMockRuntimeInfo wm) { + return """ + { + "appUrl": "%s", + "serviceType": "HOMEBOX", + "username": "%s", + "password": "%s" + } + """.formatted(wm.getHttpBaseUrl(), TEST_USER, TEST_PASS); + } } diff --git a/backend/src/test/java/com/vaessl/app/connection/ConnectionServiceTest.java b/backend/src/test/java/com/vaessl/app/connection/ConnectionServiceTest.java index 67c59e9..2543436 100644 --- a/backend/src/test/java/com/vaessl/app/connection/ConnectionServiceTest.java +++ b/backend/src/test/java/com/vaessl/app/connection/ConnectionServiceTest.java @@ -37,13 +37,14 @@ class ConnectionServiceTest { @Test void login_ShouldAbort_WhenCheckCredentialsThrowsException() { - ConnectionRequest request = new ConnectionRequest(MOCK_URL, MOCK_SERVICE_TYPE, null, null, false); + ConnectionRequest request = + new ConnectionRequest(MOCK_URL, MOCK_SERVICE_TYPE, null, null, false); - doThrow(new EmptyCredentialsException(List.of("username"))) - .when(mockProvider).checkCredentials(request); + doThrow(new EmptyCredentialsException(List.of("username"))).when(mockProvider) + .checkCredentials(request); assertThrows(EmptyCredentialsException.class, () -> connectionService.login(request)); verify(mockProvider, never()).authenticate(any()); } -} \ No newline at end of file +} diff --git a/backend/src/test/java/com/vaessl/app/connection/HomeboxIntegrationTest.java b/backend/src/test/java/com/vaessl/app/connection/HomeboxIntegrationTest.java index 16f340e..fbcd477 100644 --- a/backend/src/test/java/com/vaessl/app/connection/HomeboxIntegrationTest.java +++ b/backend/src/test/java/com/vaessl/app/connection/HomeboxIntegrationTest.java @@ -52,11 +52,10 @@ class HomeboxIntegrationTest { @Test void shouldReturnStatusOkWhenHomeboxCredentialsAreValid(WireMockRuntimeInfo wm) { - stubFor(post(HOMEBOX_LOGIN.getValue()) - .willReturn(okJson(okJsonHomeboxResponse))); + stubFor(post(HOMEBOX_LOGIN.getValue()).willReturn(okJson(okJsonHomeboxResponse))); - ResponseEntity response = restTemplate.postForEntity(LOGIN.getValue(), connectionRequest(wm), - String.class); + ResponseEntity response = + restTemplate.postForEntity(LOGIN.getValue(), connectionRequest(wm), String.class); DocumentContext documentContext = JsonPath.parse(response.getBody()); @@ -78,8 +77,8 @@ class HomeboxIntegrationTest { stubFor(post(HOMEBOX_LOGIN.getValue()).willReturn(unauthorized())); - ResponseEntity response = restTemplate.postForEntity(LOGIN.getValue(), connectionRequest(wm), - String.class); + ResponseEntity response = + restTemplate.postForEntity(LOGIN.getValue(), connectionRequest(wm), String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); assertThat(response.getBody()).contains(UNAUTHORIZED_WRONG_LOGIN.getMessage()); @@ -95,8 +94,8 @@ class HomeboxIntegrationTest { stubFor(post(HOMEBOX_LOGIN.getValue()).willReturn(serviceUnavailable())); - ResponseEntity response = restTemplate.postForEntity(LOGIN.getValue(), connectionRequest(wm), - String.class); + ResponseEntity response = + restTemplate.postForEntity(LOGIN.getValue(), connectionRequest(wm), String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); assertThat(response.getBody()).contains(SERVER_ERROR_GENERAL.getMessage()); @@ -112,7 +111,8 @@ class HomeboxIntegrationTest { .willReturn(aResponse().withFault(Fault.CONNECTION_RESET_BY_PEER))); ConnectionRequest badRequest = connectionRequest(wm); - ResponseEntity response = restTemplate.postForEntity(LOGIN.getValue(), badRequest, String.class); + ResponseEntity response = + restTemplate.postForEntity(LOGIN.getValue(), badRequest, String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); assertThat(response.getBody()).contains(SERVICE_UNAVAILABLE_UNREACHABLE_URL.getMessage()); @@ -126,34 +126,30 @@ class HomeboxIntegrationTest { ConnectionRequest emtpyRequest = new ConnectionRequest("", "", "", "", false); - ResponseEntity response = restTemplate.postForEntity(LOGIN.getValue(), emtpyRequest, String.class); + ResponseEntity response = + restTemplate.postForEntity(LOGIN.getValue(), emtpyRequest, String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); assertThat(response.getBody()).contains(BAD_REQUEST_EMPTY_FIELDS.getMessage()); } /** - * Test the exception when there is an input for serviceType but it's - * unsupported. + * Test the exception when there is an input for serviceType but it's unsupported. */ @Test void shouldReturnWrongServiceTypeException(WireMockRuntimeInfo wm) { - ConnectionRequest wrongServiceTypeReq = new ConnectionRequest( - wm.getHttpBaseUrl(), - "wrong-service-type", - TEST_USER, TEST_PASS, - false); + ConnectionRequest wrongServiceTypeReq = new ConnectionRequest(wm.getHttpBaseUrl(), + "wrong-service-type", TEST_USER, TEST_PASS, false); - ResponseEntity response = restTemplate.postForEntity(LOGIN.getValue(), wrongServiceTypeReq, - String.class); + ResponseEntity response = + restTemplate.postForEntity(LOGIN.getValue(), wrongServiceTypeReq, String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); assertThat(response.getBody()).contains(WRONG_SERVICE_TYPE.getMessage()); } /** - * Tests the succesfull persistance of Homebox credential response to the - * database. + * Tests the succesfull persistance of Homebox credential response to the database. * * @param wm the WiremockRuntimeInfo object */ @@ -165,10 +161,12 @@ class HomeboxIntegrationTest { ConnectionRequest request = connectionRequest(wm); - ResponseEntity response = restTemplate.postForEntity(LOGIN.getValue(), request, String.class); + ResponseEntity response = + restTemplate.postForEntity(LOGIN.getValue(), request, String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); - ConnectionEntity dbEntry = cRepository.findByAppUrlAndUsername(request.appUrl(), request.username()); + ConnectionEntity dbEntry = + cRepository.findByAppUrlAndUsername(request.appUrl(), request.username()); assertThat(dbEntry).isNotNull(); assertThat(dbEntry.getAppUrl()).isEqualTo(request.appUrl()); @@ -183,20 +181,18 @@ class HomeboxIntegrationTest { @Test void shouldReturnEmptyCredentialsExceptionWhenCredsAreMissing(WireMockRuntimeInfo wm) { - ConnectionRequest missingCredentials = new ConnectionRequest(wm.getHttpBaseUrl(), HOMEBOX.getValue(), TEST_USER, - null, - false); + ConnectionRequest missingCredentials = new ConnectionRequest(wm.getHttpBaseUrl(), + HOMEBOX.getValue(), TEST_USER, null, false); - ResponseEntity response = restTemplate.postForEntity(LOGIN.getValue(), missingCredentials, - String.class); + ResponseEntity response = + restTemplate.postForEntity(LOGIN.getValue(), missingCredentials, String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); assertThat(response.getBody()).contains(BAD_REQUEST_EMPTY_FIELDS.getMessage()); } /** - * Creates a valid connection request with a mock Api through - * WireMockRuntimeInfo. + * Creates a valid connection request with a mock Api through WireMockRuntimeInfo. * * @param wm the WiremockRuntimeInfo object * @return a mock api connection request.