Assessment review: Malformed UUID/page parameters currently return 500, and non-PDF/empty uploads return 201. These are verified defects, not the desired API behavior. See F3 and F4.
The HTTP contract is an external model. Keeping it distinct from domain and persistence models lets the API evolve without publishing database internals.
Follow the upload boundary
DocumentController implements generated DocumentsApi. It receives MultipartFile, supplies fallback filename/content type, reads bytes, and creates DocumentUpload. The service receives a Kotlin model rather than the HTTP upload abstraction. The controller maps the result into DocumentResponse and builds the creation response.
This is a real boundary with a practical limitation: reading document.bytes buffers the upload in memory. A streaming upload port would be a separate improvement, with different lifetime and retry rules. Do not claim the existing code streams large files.
Three models, three responsibilities
| Representation | Owns | Must not decide |
|---|---|---|
| Generated request/response DTO | Wire fields and validation metadata | Whether the current actor can modify a document |
| Domain model/command | Application meaning and update intent | HTTP status codes or JPA relationship fetching |
| JPA entity | Persistence identity, relationships, versioning | Response shape or caller permissions |
Bean Validation handles structural constraints. Service guards handle contextual rules such as whether a supplied team exists and whether sharing may change. Exception translation turns failures into HTTP responses through GlobalExceptionHandler; examine its concrete cases rather than assuming every exception becomes 400.
Partial updates need intent
DocumentUpdate carries teamId and clearTeam, plus equivalent document-type fields. Sending both a new ID and a clear flag is contradictory and rejected by the service. An omitted value preserves the existing field. A nullable generated DTO alone cannot necessarily distinguish missing input from explicit null; the build selects openApiNullable=false.
Practice
Write a table for four update requests: no sharing fields, a new team ID, clear sharing, and new team ID plus clear flag. Predict the service branch and expected persistence call for each. Repeat for document type. Then inspect the existing conflict and request validation tests.
In your practice checkout, add a response-only property to the authoritative OpenAPI schema. Regenerate, compile, and inspect which mapping needs an explicit decision. Keep entity objects out of response types.
Verification gate
Trace one successful upload and one contradictory update from generated API contract to service exception to HTTP translation. Explain why checking existence in a controller would make other service callers bypass that check.
Read the implementation
- DocumentController.kt
- DocumentUpdate.kt
- GlobalExceptionHandler.kt
- DocumentTypeRequestValidationTest.kt
Complete source walkthrough
Read these pinned files alongside the explanation above. These are the inspected implementation, not the capstone solution.
DocumentController.kt
package at.fhtw.swen3.paperless.document.controller
import at.fhtw.swen3.paperless.api.DocumentsApi
import at.fhtw.swen3.paperless.dto.DocumentResponse
import at.fhtw.swen3.paperless.dto.DocumentPageResponse
import at.fhtw.swen3.paperless.dto.UpdateDocumentRequest
import at.fhtw.swen3.paperless.document.mapper.DocumentMapper
import at.fhtw.swen3.paperless.document.model.DocumentUpload
import at.fhtw.swen3.paperless.document.service.DocumentService
import at.fhtw.swen3.paperless.dto.PageMetadata
import org.springframework.core.io.Resource
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.multipart.MultipartFile
import java.net.URI
import java.util.UUID
@RestController
class DocumentController(
private val documentService: DocumentService,
private val documentMapper: DocumentMapper
) : DocumentsApi {
override fun getDocumentById(id: UUID): ResponseEntity<DocumentResponse> {
val document = documentService.getDocument(id)
val response = documentMapper.toDto(document)
return ResponseEntity.ok(response)
}
override fun searchDocuments(
page: Int,
size: Int,
sort: String,
documentTypeId: UUID?
): ResponseEntity<DocumentPageResponse> {
val documents = documentService.searchDocuments(page, size, sort, documentTypeId)
val items = documents.content.map(documentMapper::toDto)
val pagination = PageMetadata(page, size, documents.totalElements, documents.totalPages)
return ResponseEntity.ok(DocumentPageResponse(pagination, items))
}
override fun uploadDocument(
document: MultipartFile,
title: String,
documentTypeId: UUID?,
teamId: UUID?
): ResponseEntity<DocumentResponse> {
val upload = DocumentUpload(
title = title,
originalFilename = document.originalFilename ?: "document",
contentType = document.contentType ?: MediaType.APPLICATION_OCTET_STREAM_VALUE,
content = document.bytes,
documentTypeId = documentTypeId,
teamId = teamId
)
val created = documentService.uploadDocument(upload)
val response = documentMapper.toDto(created)
return ResponseEntity.created(URI.create("/api/v1/documents/${created.id}")).body(response)
}
override fun updateDocumentMetadata(
id: UUID,
updateDocumentRequest: UpdateDocumentRequest
): ResponseEntity<DocumentResponse> {
val update = documentMapper.toUpdateModel(updateDocumentRequest)
val document = documentService.updateDocument(id, update)
val response = documentMapper.toDto(document)
return ResponseEntity.ok(response)
}
override fun deleteDocument(id: UUID): ResponseEntity<Unit> {
documentService.deleteDocument(id)
return ResponseEntity.noContent().build()
}
override fun downloadDocumentFile(id: UUID): ResponseEntity<Resource> {
val resource = documentService.downloadDocument(id)
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"${resource.filename}\"")
.body(resource)
}
}
DocumentUpdate.kt
package at.fhtw.swen3.paperless.document.model
import java.util.UUID
data class DocumentUpdate(
val teamId: UUID?,
val clearTeam: Boolean,
val title: String?,
val documentTypeId: UUID?,
val clearDocumentType: Boolean = false
)
GlobalExceptionHandler.kt
package at.fhtw.swen3.paperless.exception
import at.fhtw.swen3.paperless.dto.InvalidParam
import at.fhtw.swen3.paperless.dto.Problem
import jakarta.validation.ConstraintViolationException
import jakarta.persistence.OptimisticLockException
import org.slf4j.LoggerFactory
import org.springframework.dao.DataIntegrityViolationException
import org.springframework.orm.ObjectOptimisticLockingFailureException
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.http.converter.HttpMessageNotReadableException
import org.springframework.security.access.AccessDeniedException
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.multipart.MaxUploadSizeExceededException
import org.springframework.web.servlet.resource.NoResourceFoundException
import java.net.URI
@RestControllerAdvice
class GlobalExceptionHandler {
@ExceptionHandler(AppException::class)
fun handleAppException(exception: AppException): ResponseEntity<Problem> {
return problem(exception.error)
}
@ExceptionHandler(MethodArgumentNotValidException::class)
fun handleValidationException(exception: MethodArgumentNotValidException): ResponseEntity<Problem> {
val invalidParams = exception.bindingResult.fieldErrors.map {
InvalidParam(it.field, it.defaultMessage ?: "Invalid value.")
}
return problem(
status = HttpStatus.BAD_REQUEST,
title = "Bad Request",
detail = "One or more request fields are invalid.",
invalidParams = invalidParams
)
}
@ExceptionHandler(ConstraintViolationException::class, HttpMessageNotReadableException::class)
fun handleBadRequest(exception: Exception): ResponseEntity<Problem> =
problem(
status = HttpStatus.BAD_REQUEST,
title = "Bad Request",
detail = exception.message ?: "The request is invalid."
)
@ExceptionHandler(DataIntegrityViolationException::class, OptimisticLockException::class, ObjectOptimisticLockingFailureException::class)
fun handleConflict(): ResponseEntity<Problem> =
problem(
status = HttpStatus.CONFLICT,
title = "Conflict",
detail = "The request conflicts with an existing resource."
)
@ExceptionHandler(AccessDeniedException::class)
fun handleAccessDenied(): ResponseEntity<Problem> =
problem(HttpStatus.FORBIDDEN, "Forbidden", "Access is denied.")
@ExceptionHandler(NoResourceFoundException::class)
fun handleNoResourceFound(exception: NoResourceFoundException): ResponseEntity<Problem> =
problem(HttpStatus.NOT_FOUND, "Resource Not Found", "The requested resource was not found.")
@ExceptionHandler(MaxUploadSizeExceededException::class)
fun handleMaxUploadSizeExceeded(): ResponseEntity<Problem> =
problem(
HttpStatus.PAYLOAD_TOO_LARGE,
"Payload Too Large",
"The uploaded content exceeds the maximum allowed size."
)
@ExceptionHandler(Exception::class)
fun handleUnexpectedException(exception: Exception): ResponseEntity<Problem> {
logger.error(
"[API] - ACTION: unexpectedFailure: exceptionType: {}, stackTrace: {}",
exception.javaClass.name,
exception.stackTrace.contentToString()
)
return problem(AppErrorMessage.INTERNAL_SERVER_ERROR)
}
private fun problem(error: AppErrorMessage): ResponseEntity<Problem> =
problem(error.status, error.title, error.detail)
private fun problem(
status: HttpStatus,
title: String,
detail: String,
invalidParams: List<InvalidParam>? = null
): ResponseEntity<Problem> {
if (status.is4xxClientError) {
logger.warn("[API] - ACTION: rejectRequest: status: {}, title: {}", status.value(), title)
}
val response = Problem(
type = URI.create("urn:problem-type:${status.value()}"),
title = title,
status = status.value(),
detail = detail,
invalidParams = invalidParams
)
return ResponseEntity.status(status).body(response)
}
private companion object {
val logger = LoggerFactory.getLogger(GlobalExceptionHandler::class.java)
}
}
DocumentTypeRequestValidationTest.kt
package at.fhtw.swen3.paperless.documenttype
import at.fhtw.swen3.paperless.documenttype.entity.DocumentTypeEntity
import at.fhtw.swen3.paperless.documenttype.persistence.repository.DocumentTypeRepository
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc
import org.springframework.http.MediaType
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
import java.util.UUID
@SpringBootTest(properties = [
"spring.datasource.url=jdbc:h2:mem:namevalidation;DB_CLOSE_DELAY=-1",
"spring.datasource.driver-class-name=org.h2.Driver",
"spring.jpa.database-platform=org.hibernate.dialect.H2Dialect",
"spring.jpa.hibernate.ddl-auto=create-drop"
])
@AutoConfigureMockMvc
class DocumentTypeRequestValidationTest(
@Autowired private val mvc: MockMvc,
@Autowired private val repository: DocumentTypeRepository
) {
@Test
fun whitespace_only_name_is_rejected_with_bad_request() {
mvc.perform(
post("/api/v1/document-types")
.with(user("name-validation"))
.contentType(MediaType.APPLICATION_JSON)
.content("""{"name":" "}""")
).andExpect(status().isBadRequest)
}
@Test
fun generated_id_is_uuid() {
val saved = repository.save(DocumentTypeEntity(name = "UUID generated document type"))
assertThat(saved.id).isInstanceOf(UUID::class.java)
}
}