# 01 — Build graph and the first request

> **Assessment review:** The API description promises processing that this baseline does not implement. Compile success is not use-case completion. See [F1 and the grading matrix](../review.md#f1-background-processing-is-missing-from-the-checked-out-baseline).

Start with the executable system: a Kotlin JVM Spring Boot backend with generated HTTP contracts, JPA persistence, and database migrations. This course uses the backend at commit `28ef27347fb16e076f24449a78072f480bd443d9`, captured on 2026-10-26. Work in your own practice checkout. The bundled reference preserves the inspected files independently of the original directory.

## What you will build

Reconstruct a small document-management vertical slice, then explain the existing implementation from HTTP to database and back. You should already understand Java classes, interfaces, HTTP requests, and basic SQL. The course emphasizes architectural decisions and failure behavior; the frontend is outside its scope.

The build pins Kotlin 2.3.21, Spring Boot 4.1.1, MapStruct 1.6.3, OpenAPI Generator 7.11.0, and a Java 25 toolchain. These are the inspected project's versions, not an instruction to upgrade another project.

## Follow the build graph

`src/main/resources/openapi.yaml` is the backend generation input. The similarly named file under repository `docs/` is not the input selected by this build. `openApiGenerate` creates Kotlin interfaces and DTOs under `build/generated/openapi`. Both Kotlin compilation and kapt stub generation depend on it. kapt then makes MapStruct's Java annotation processor usable for Kotlin mapper declarations. Generated output belongs under `build/`; change its input rather than editing an implementation that regeneration will replace.

The Spring compiler plugin supports framework proxying. The JPA plugin and explicit `allOpen` entity annotations support JPA construction/proxy requirements. These solve framework integration concerns; they do not make domain models JPA entities.

## Trace one request

For `getDocumentById`, the controller delegates to `DocumentService`, then maps the returned domain `Document` to a response. `DocumentServiceImpl` loads through `DocumentPersistence`, enforces readability for the current actor, and returns a model. The JPA adapter converts an entity before the service receives it. Keep HTTP response creation in the controller and access decisions in the service.

## Practice

1. Draw the compilation order: OpenAPI → Kotlin stubs → MapStruct generation → compilation.
2. In a practice checkout, run the wrapper from `paperless-backend`: `./gradlew compileKotlin`.
3. Locate the generated `DocumentsApi`, DTOs, and mapper implementation under `build/generated`. Compare them with their source inputs.
4. Trace the same request with a missing document and with a document invisible to the actor.

## Verification gate

Explain why a mapper can compile only after its generated DTO types exist. Identify the one source contract to edit when adding a response property. Record your own command results; this course's website checks do not establish that the backend builds on your machine.

## Read the implementation

- [build.gradle.kts](../reference/source/paperless-backend/build.gradle.kts)
- [settings.gradle.kts](../reference/source/paperless-backend/settings.gradle.kts)
- [PaperlessApplication.kt](../reference/source/paperless-backend/src/main/kotlin/at/fhtw/swen3/paperless/PaperlessApplication.kt)
- [DocumentController.kt](../reference/source/paperless-backend/src/main/kotlin/at/fhtw/swen3/paperless/document/controller/DocumentController.kt)

## Complete source walkthrough

Read these pinned files alongside the explanation above. These are the inspected implementation, not the capstone solution.

### build.gradle.kts

[Browse source](../reference/source/paperless-backend/build.gradle.kts)

```kotlin
plugins {
    kotlin("jvm") version "2.3.21"
    kotlin("plugin.spring") version "2.3.21"
    kotlin("plugin.jpa") version "2.3.21"
    id("org.springframework.boot") version "4.1.1"
    id("io.spring.dependency-management") version "1.1.7"
    id("org.openapi.generator") version "7.11.0"
    kotlin("kapt") version "2.3.21"
}

group = "at.fhtw.swen3"
version = "0.0.2-SNAPSHOT"

java {
    toolchain {
        languageVersion.set(JavaLanguageVersion.of(25))
    }
}


repositories {
    mavenCentral()
}

dependencies {
    implementation("org.springframework.boot:spring-boot-h2console")
    implementation("org.springframework.boot:spring-boot-starter-data-jpa")
    implementation("org.springframework.boot:spring-boot-starter-flyway")
    implementation("org.springframework.boot:spring-boot-starter-security")
    implementation("org.springframework.boot:spring-boot-starter-oauth2-resource-server")
    implementation("org.springframework.boot:spring-boot-starter-validation")
    implementation("org.springframework.boot:spring-boot-starter-webmvc")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    implementation("org.jetbrains.kotlin:kotlin-stdlib")
    implementation("tools.jackson.module:jackson-module-kotlin")
    implementation("org.mapstruct:mapstruct:1.6.3")

    implementation("org.springdoc:springdoc-openapi-starter-webmvc-ui:3.1.1")
    implementation("org.openapitools:jackson-databind-nullable:0.2.6")

    developmentOnly("org.springframework.boot:spring-boot-devtools")
    runtimeOnly("com.h2database:h2")
    runtimeOnly("org.flywaydb:flyway-database-postgresql")
    runtimeOnly("org.postgresql:postgresql")

    kapt("org.springframework.boot:spring-boot-configuration-processor")
    kapt("org.mapstruct:mapstruct-processor:1.6.3")

    testImplementation("org.springframework.boot:spring-boot-starter-data-jpa-test")
    testImplementation("org.springframework.boot:spring-boot-starter-security-test")
    testImplementation("org.springframework.boot:spring-boot-starter-validation-test")
    testImplementation("org.springframework.boot:spring-boot-starter-webmvc-test")
    testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")
    testImplementation(kotlin("test"))
}

kotlin {
    compilerOptions {
        freeCompilerArgs.addAll("-Xjsr305=strict", "-Xannotation-default-target=param-property")
    }
    sourceSets {
        main {
            kotlin.srcDir(layout.buildDirectory.dir("generated/openapi/src/main/kotlin"))
        }
    }
}

allOpen {
    annotation("jakarta.persistence.Entity")
    annotation("jakarta.persistence.MappedSuperclass")
    annotation("jakarta.persistence.Embeddable")
}

openApiGenerate {
    generatorName.set("kotlin-spring")
    inputSpec.set("$projectDir/src/main/resources/openapi.yaml")
    outputDir.set(layout.buildDirectory.dir("generated/openapi").get().asFile.path)
    apiPackage.set("at.fhtw.swen3.paperless.api")
    modelPackage.set("at.fhtw.swen3.paperless.dto")
    configOptions.set(
        mapOf(
            "interfaceOnly" to "true",
            "useSpringBoot3" to "true",
            "useBeanValidation" to "true",
            "enumPropertyNaming" to "UPPERCASE",
            "openApiNullable" to "false",
            "useTags" to "true"
        )
    )
}

tasks.named("compileKotlin") {
    dependsOn("openApiGenerate")
}

tasks.matching { it.name == "kaptGenerateStubsKotlin" }.configureEach {
    dependsOn("openApiGenerate")
}

tasks.withType<Test> {
    useJUnitPlatform()
}
```

### settings.gradle.kts

[Browse source](../reference/source/paperless-backend/settings.gradle.kts)

```kotlin
rootProject.name = "paperless"
```

### PaperlessApplication.kt

[Browse source](../reference/source/paperless-backend/src/main/kotlin/at/fhtw/swen3/paperless/PaperlessApplication.kt)

```kotlin
package at.fhtw.swen3.paperless

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication

@SpringBootApplication
class PaperlessApplication

fun main(args: Array<String>) {
	runApplication<PaperlessApplication>(*args)
}
```

### DocumentController.kt

[Browse source](../reference/source/paperless-backend/src/main/kotlin/at/fhtw/swen3/paperless/document/controller/DocumentController.kt)

```kotlin
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)
    }
}
```
