From 8aba23c9211c73b4aebd408029d2f5ae10f860dc Mon Sep 17 00:00:00 2001 From: querwurzel <> Date: Sun, 15 Dec 2024 19:42:07 +0100 Subject: [PATCH] chore: formatting, rm useless code --- .../binpastes/paste/api/PasteController.java | 75 ++++---- .../paste/application/model/CreateCmd.java | 28 +-- .../paste/application/model/DetailView.java | 70 +++++--- .../paste/application/model/ListView.java | 33 ++-- .../paste/application/model/SearchView.java | 32 ++-- .../binpastes/paste/OneTimePasteIT.java | 162 +++++++++--------- 6 files changed, 205 insertions(+), 195 deletions(-) diff --git a/backend/src/main/java/com/github/binpastes/paste/api/PasteController.java b/backend/src/main/java/com/github/binpastes/paste/api/PasteController.java index 1c6bbda..60cd02a 100644 --- a/backend/src/main/java/com/github/binpastes/paste/api/PasteController.java +++ b/backend/src/main/java/com/github/binpastes/paste/api/PasteController.java @@ -35,7 +35,6 @@ import java.nio.charset.Charset; import java.time.Duration; import java.time.LocalDateTime; -import java.util.Optional; @Validated @RestController @@ -53,41 +52,41 @@ public PasteController(final PasteViewService pasteViewService) { @GetMapping("/{pasteId:[a-z0-9]{40}}") public Mono findPaste( - @PathVariable("pasteId") - final String pasteId, - final ServerHttpRequest request, - final ServerHttpResponse response + @PathVariable("pasteId") + final String pasteId, + final ServerHttpRequest request, + final ServerHttpResponse response ) { return pasteViewService - .viewPaste(pasteId, remoteAddress(request).orElse(null)) - .doOnNext(paste -> { - if (paste.isOneTime()) { - response.getHeaders().setCacheControl(CacheControl.noStore()); - return; - } - - var now = LocalDateTime.now(); - if (paste.isPermanent() || paste.dateOfExpiry().get().plusMinutes(1).isAfter(now)) { - response.getHeaders().setCacheControl( - CacheControl.maxAge(Duration.ofMinutes(1))); - } else { - response.getHeaders().setCacheControl( - CacheControl.maxAge(Duration.between(now, paste.dateOfExpiry().get())).mustRevalidate()); - } - }) - .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND))); + .viewPaste(pasteId, remoteAddress(request)) + .doOnNext(paste -> { + if (paste.isOneTime()) { + response.getHeaders().setCacheControl(CacheControl.noStore()); + return; + } + + var now = LocalDateTime.now(); + if (paste.isPermanent() || paste.dateOfExpiry().get().plusMinutes(1).isAfter(now)) { + response.getHeaders().setCacheControl( + CacheControl.maxAge(Duration.ofMinutes(1))); + } else { + response.getHeaders().setCacheControl( + CacheControl.maxAge(Duration.between(now, paste.dateOfExpiry().get())).mustRevalidate()); + } + }) + .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND))); } @PostMapping("/{pasteId:[a-z0-9]{40}}") public Mono findAndBurnOneTimePaste( - @PathVariable("pasteId") - final String pasteId, - final ServerHttpResponse response + @PathVariable("pasteId") + final String pasteId, + final ServerHttpResponse response ) { response.getHeaders().setCacheControl(CacheControl.noStore()); return pasteViewService - .viewOneTimePaste(pasteId) - .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND))); + .viewOneTimePaste(pasteId) + .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND))); } @GetMapping @@ -97,11 +96,11 @@ public Mono findPastes() { @GetMapping("/search") public Mono searchPastes( - @RequestParam("term") - @NotBlank - @Pattern(regexp = "[\\p{L}\\p{N}\\p{P}\\s]{3,50}") - final String term, - final ServerHttpResponse response + @RequestParam("term") + @NotBlank + @Pattern(regexp = "[\\p{L}\\p{N}\\p{P}\\s]{3,50}") + final String term, + final ServerHttpResponse response ) { var decodedTerm = URLDecoder.decode(term, Charset.defaultCharset()); response.getHeaders().setCacheControl(CacheControl.maxAge(Duration.ofMinutes(1))); @@ -111,13 +110,13 @@ public Mono searchPastes( @PostMapping @ResponseStatus(HttpStatus.CREATED) public Mono createPaste(@Valid @RequestBody final CreateCmd createCmd, final ServerHttpRequest request) { - return pasteViewService.createPaste(createCmd, remoteAddress(request).orElse(null)); + return pasteViewService.createPaste(createCmd, remoteAddress(request)); } @DeleteMapping("/{pasteId:[a-z0-9]{40}}") @ResponseStatus(HttpStatus.NO_CONTENT) public Mono deletePaste(@PathVariable("pasteId") final String pasteId, final ServerHttpRequest request) { - return pasteViewService.requestDeletion(pasteId, remoteAddress(request).orElse(null)); + return pasteViewService.requestDeletion(pasteId, remoteAddress(request)); } @ExceptionHandler({ConstraintViolationException.class, WebExchangeBindException.class}) @@ -126,15 +125,15 @@ private void handleValidationException(final RuntimeException e) { log.info("Received invalid request [{}]: {}", e.getClass().getSimpleName(), e.getMessage()); } - private static Optional remoteAddress(final ServerHttpRequest request) { + private static String remoteAddress(final ServerHttpRequest request) { if (request.getHeaders().containsKey("X-Forwarded-For")) { - return Optional.of(request.getHeaders().getFirst("X-Forwarded-For")); + return request.getHeaders().getFirst("X-Forwarded-For"); } if (request.getRemoteAddress() == null) { - return Optional.empty(); + return null; } - return Optional.ofNullable(request.getRemoteAddress().getAddress().getHostAddress()); + return request.getRemoteAddress().getAddress().getHostAddress(); } } diff --git a/backend/src/main/java/com/github/binpastes/paste/application/model/CreateCmd.java b/backend/src/main/java/com/github/binpastes/paste/application/model/CreateCmd.java index 6b04404..ac41042 100644 --- a/backend/src/main/java/com/github/binpastes/paste/application/model/CreateCmd.java +++ b/backend/src/main/java/com/github/binpastes/paste/application/model/CreateCmd.java @@ -1,6 +1,6 @@ package com.github.binpastes.paste.application.model; -import com.github.binpastes.paste.domain.Paste; +import com.github.binpastes.paste.domain.Paste.PasteExposure; import com.github.binpastes.util.NullOrNotBlank; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; @@ -19,14 +19,14 @@ public final class CreateCmd { private final String content; private final Boolean isEncrypted; private final ExpirationRange expiry; - private final Paste.PasteExposure exposure; + private final PasteExposure exposure; private CreateCmd( - final String title, - final String content, - final Boolean isEncrypted, - final ExpirationRange expiry, - final Paste.PasteExposure exposure + final String title, + final String content, + final Boolean isEncrypted, + final ExpirationRange expiry, + final PasteExposure exposure ) { this.title = title; this.content = content; @@ -37,8 +37,8 @@ private CreateCmd( public String title() { return title == null - ? null - : title.strip(); + ? null + : title.strip(); } public String content() { @@ -51,14 +51,14 @@ public boolean isEncrypted() { public LocalDateTime dateOfExpiry() { return expiry == null - ? ExpirationRange.ONE_DAY.toTimestamp() // default expiry if not set - : expiry.toTimestamp(); + ? ExpirationRange.ONE_DAY.toTimestamp() // default expiry if not set + : expiry.toTimestamp(); } - public Paste.PasteExposure pasteExposure() { + public PasteExposure pasteExposure() { return exposure == null - ? Paste.PasteExposure.PUBLIC // default exposure if not set - : exposure; + ? PasteExposure.PUBLIC // default exposure if not set + : exposure; } private enum ExpirationRange { diff --git a/backend/src/main/java/com/github/binpastes/paste/application/model/DetailView.java b/backend/src/main/java/com/github/binpastes/paste/application/model/DetailView.java index 7062965..9019401 100644 --- a/backend/src/main/java/com/github/binpastes/paste/application/model/DetailView.java +++ b/backend/src/main/java/com/github/binpastes/paste/application/model/DetailView.java @@ -9,35 +9,53 @@ @JsonInclude(Include.NON_DEFAULT) public record DetailView( - String id, - Optional title, - String content, - int sizeInBytes, - boolean isPublic, - boolean isErasable, - boolean isEncrypted, - boolean isOneTime, - boolean isPermanent, - LocalDateTime dateCreated, - Optional dateOfExpiry, - Optional lastViewed, - long views + String id, + Optional title, + String content, + int sizeInBytes, + boolean isPublic, + boolean isErasable, + boolean isEncrypted, + boolean isOneTime, + boolean isPermanent, + LocalDateTime dateCreated, + Optional dateOfExpiry, + Optional lastViewed, + long views ) { public static DetailView of(final Paste reference, final String remoteAddress) { return new DetailView( - reference.getId(), - reference.getTitle(), - reference.getContent(), - reference.getContent().getBytes().length, - reference.isPublic(), - reference.isErasable(remoteAddress), - reference.isEncrypted(), - reference.isOneTime(), - reference.isPermanent(), - reference.getDateCreated(), - reference.getDateOfExpiry(), - reference.getLastViewed(), - reference.getViews() + reference.getId(), + reference.getTitle(), + reference.getContent(), + reference.getContent().getBytes().length, + reference.isPublic(), + reference.isErasable(remoteAddress), + reference.isEncrypted(), + reference.isOneTime(), + reference.isPermanent(), + reference.getDateCreated(), + reference.getDateOfExpiry(), + reference.getLastViewed(), + reference.getViews() + ); + } + + public static DetailView ofOneTime(final Paste reference, final String remoteAddress) { + return new DetailView( + reference.getId(), + null, + null, + 0, + reference.isPublic(), + reference.isErasable(remoteAddress), + reference.isEncrypted(), + reference.isOneTime(), + reference.isPermanent(), + reference.getDateCreated(), + reference.getDateOfExpiry(), + reference.getLastViewed(), + reference.getViews() ); } } diff --git a/backend/src/main/java/com/github/binpastes/paste/application/model/ListView.java b/backend/src/main/java/com/github/binpastes/paste/application/model/ListView.java index 9d38574..636a2da 100644 --- a/backend/src/main/java/com/github/binpastes/paste/application/model/ListView.java +++ b/backend/src/main/java/com/github/binpastes/paste/application/model/ListView.java @@ -9,31 +9,28 @@ import java.util.Optional; public record ListView( - List pastes + List pastes ) { - public static ListView of(final List pastes) { - return new ListView(pastes); - } @JsonInclude(Include.NON_DEFAULT) public record ListItemView( - String id, - Optional title, - int sizeInBytes, - boolean isEncrypted, - boolean isPermanent, - LocalDateTime dateCreated, - Optional dateOfExpiry + String id, + Optional title, + int sizeInBytes, + boolean isEncrypted, + boolean isPermanent, + LocalDateTime dateCreated, + Optional dateOfExpiry ) { public static ListItemView of(final Paste reference) { return new ListItemView( - reference.getId(), - reference.getTitle(), - reference.getContent().getBytes().length, - reference.isEncrypted(), - reference.isPermanent(), - reference.getDateCreated(), - reference.getDateOfExpiry() + reference.getId(), + reference.getTitle(), + reference.getContent().getBytes().length, + reference.isEncrypted(), + reference.isPermanent(), + reference.getDateCreated(), + reference.getDateOfExpiry() ); } } diff --git a/backend/src/main/java/com/github/binpastes/paste/application/model/SearchView.java b/backend/src/main/java/com/github/binpastes/paste/application/model/SearchView.java index 463c3bd..e3b9737 100644 --- a/backend/src/main/java/com/github/binpastes/paste/application/model/SearchView.java +++ b/backend/src/main/java/com/github/binpastes/paste/application/model/SearchView.java @@ -9,33 +9,29 @@ import java.util.Optional; public record SearchView( - List pastes + List pastes ) { - public static SearchView of(List pastes) { - return new SearchView(pastes); - } - @JsonInclude(Include.NON_DEFAULT) public record SearchItemView( - String id, - Optional title, - String highlight, - int sizeInBytes, - LocalDateTime dateCreated, - Optional dateOfExpiry + String id, + Optional title, + String highlight, + int sizeInBytes, + LocalDateTime dateCreated, + Optional dateOfExpiry ) { private static final short HIGHLIGHT_RANGE = 30; public static SearchItemView of(final Paste reference, final String term) { return new SearchItemView( - reference.getId(), - reference.getTitle(), - highlight(reference.getContent(), term), - reference.getContent().getBytes().length, - reference.getDateCreated(), - reference.getDateOfExpiry() + reference.getId(), + reference.getTitle(), + highlight(reference.getContent(), term), + reference.getContent().getBytes().length, + reference.getDateCreated(), + reference.getDateOfExpiry() ); } @@ -47,7 +43,7 @@ public static String highlight(final String content, final String term) { } final int leftRemainder = Math.abs(Math.min(0, idx - HIGHLIGHT_RANGE)); - final int rightRemainder = Math.max(0, idx + HIGHLIGHT_RANGE - content.length()); + final int rightRemainder = Math.max(0, (idx + HIGHLIGHT_RANGE) - content.length()); return content.substring( Math.max(0, idx - HIGHLIGHT_RANGE - rightRemainder), diff --git a/backend/src/test/java/com/github/binpastes/paste/OneTimePasteIT.java b/backend/src/test/java/com/github/binpastes/paste/OneTimePasteIT.java index 27d7993..6222f29 100644 --- a/backend/src/test/java/com/github/binpastes/paste/OneTimePasteIT.java +++ b/backend/src/test/java/com/github/binpastes/paste/OneTimePasteIT.java @@ -51,21 +51,21 @@ void getOneTimePasteHidesContent() { var oneTimePaste = givenOneTimePaste(); webClient.get() - .uri("/api/v1/paste/{id}", oneTimePaste.getId()) - .exchange() - .expectStatus().isOk() - .expectHeader().cacheControl(CacheControl.noStore()) - .expectBody() - .jsonPath("$.content").doesNotExist() - .jsonPath("$.title").doesNotExist() - .jsonPath("$.sizeInBytes").doesNotExist() - .json(""" - { - "isErasable": true, - "isOneTime": true, - "isPermanent" :true - } - """); + .uri("/api/v1/paste/{id}", oneTimePaste.getId()) + .exchange() + .expectStatus().isOk() + .expectHeader().cacheControl(CacheControl.noStore()) + .expectBody() + .jsonPath("$.content").doesNotExist() + .jsonPath("$.title").doesNotExist() + .jsonPath("$.sizeInBytes").doesNotExist() + .json(""" + { + "isErasable": true, + "isOneTime": true, + "isPermanent" :true + } + """); } @Test @@ -78,9 +78,9 @@ void viewOneTimePasteConcurrently() { final Runnable request = () -> { try { webClient.post() - .uri("/api/v1/paste/{id}", oneTimePaste.getId()) - .exchange() - .expectStatus().isOk(); + .uri("/api/v1/paste/{id}", oneTimePaste.getId()) + .exchange() + .expectStatus().isOk(); okCount.incrementAndGet(); } catch (AssertionError ex) { @@ -91,11 +91,11 @@ void viewOneTimePasteConcurrently() { }; Flux.fromStream(Stream.generate(() -> request)) - .take(50) - .parallel() - .doOnNext(Runnable::run) - .runOn(Schedulers.boundedElastic()) - .subscribe(); + .take(50) + .parallel() + .doOnNext(Runnable::run) + .runOn(Schedulers.boundedElastic()) + .subscribe(); assertThat(okCount.get()).isOne(); assertThat(notFoundCount.get()).isEqualTo(50 - 1); @@ -109,10 +109,10 @@ void findAllPastes() { assertThat(pasteRepository.count().block()).isOne(); webClient.get() - .uri("/api/v1/paste") - .exchange() - .expectStatus().isOk() - .expectBody().jsonPath("pastes", emptyList()); + .uri("/api/v1/paste") + .exchange() + .expectStatus().isOk() + .expectBody().jsonPath("pastes", emptyList()); } @Test @@ -123,10 +123,10 @@ void searchAllPastes() { assertThat(pasteRepository.count().block()).isOne(); webClient.get() - .uri("/api/v1/paste/search?term={term}", oneTimePaste.getTitle().get()) - .exchange() - .expectStatus().isOk() - .expectBody().jsonPath("pastes", emptyList()); + .uri("/api/v1/paste/search?term={term}", oneTimePaste.getTitle().get()) + .exchange() + .expectStatus().isOk() + .expectBody().jsonPath("pastes", emptyList()); } @Test @@ -134,40 +134,40 @@ void searchAllPastes() { void createOneTimePaste() { var now = LocalDateTime.now(); webClient.post() - .uri("/api/v1/paste") - .contentType(MediaType.APPLICATION_JSON) - .body(Mono.just(""" - { - "title": "someTitle", - "content": "someContent", - "exposure": "ONCE", - "isEncrypted": true, - "expiry": "THREE_MONTHS" - } - """), String.class) - .exchange() - .expectStatus().isCreated() - .expectHeader().cacheControl(CacheControl.empty()) - .expectBody() - .jsonPath("$.id").value(id -> - assertThat(id).matches("^[a-z0-9]{40}$") - ) - .jsonPath("$.dateCreated").value(dateCreated -> - assertThat(parse(dateCreated)).isCloseTo(now, new TemporalUnitLessThanOffset(3, ChronoUnit.SECONDS)) - ) - .jsonPath("$.dateOfExpiry").value(dateOfExpiry -> - assertThat(parse(dateOfExpiry)).isCloseTo(now.plusMonths(3), new TemporalUnitLessThanOffset(3, ChronoUnit.SECONDS)) - ) - .jsonPath("$.content").doesNotExist() - .jsonPath("$.title").doesNotExist() - .jsonPath("$.sizeInBytes").doesNotExist() - .json(""" - { - "isErasable": true, - "isEncrypted": true, - "isOneTime": true - } - """); + .uri("/api/v1/paste") + .contentType(MediaType.APPLICATION_JSON) + .body(Mono.just(""" + { + "title": "someTitle", + "content": "someContent", + "exposure": "ONCE", + "isEncrypted": true, + "expiry": "THREE_MONTHS" + } + """), String.class) + .exchange() + .expectStatus().isCreated() + .expectHeader().cacheControl(CacheControl.empty()) + .expectBody() + .jsonPath("$.id").value(id -> + assertThat(id).matches("^[a-z0-9]{40}$") + ) + .jsonPath("$.dateCreated").value(dateCreated -> + assertThat(parse(dateCreated)).isCloseTo(now, new TemporalUnitLessThanOffset(3, ChronoUnit.SECONDS)) + ) + .jsonPath("$.dateOfExpiry").value(dateOfExpiry -> + assertThat(parse(dateOfExpiry)).isCloseTo(now.plusMonths(3), new TemporalUnitLessThanOffset(3, ChronoUnit.SECONDS)) + ) + .jsonPath("$.content").doesNotExist() + .jsonPath("$.title").doesNotExist() + .jsonPath("$.sizeInBytes").doesNotExist() + .json(""" + { + "isErasable": true, + "isEncrypted": true, + "isOneTime": true + } + """); } @Test @@ -176,29 +176,29 @@ void deleteOneTimePaste() { var oneTimePaste = givenOneTimePaste(); webClient.delete() - .uri("/api/v1/paste/{id}", oneTimePaste.getId()) - .exchange() - .expectStatus().isNoContent() - .expectBody().isEmpty(); + .uri("/api/v1/paste/{id}", oneTimePaste.getId()) + .exchange() + .expectStatus().isNoContent() + .expectBody().isEmpty(); waitAtMost(ofMillis(500)).untilAsserted(() -> webClient - .get() - .uri("/api/v1/paste/{id}", oneTimePaste.getId()) - .exchange() - .expectStatus().isNotFound() + .get() + .uri("/api/v1/paste/{id}", oneTimePaste.getId()) + .exchange() + .expectStatus().isNotFound() ); } private Paste givenOneTimePaste() { return persistedPaste( - Paste.newInstance( - "someTitle", - "Lorem ipsum dolor sit amet", - false, - PasteExposure.ONCE, - null, - "1.1.1.1" - ) + Paste.newInstance( + "someTitle", + "Lorem ipsum dolor sit amet", + false, + PasteExposure.ONCE, + null, + "1.1.1.1" + ) ); }