Assessment review: The original API promises automatic extraction/indexing, but this baseline only searches available stored fields in memory. Distinguish the implementation from the promised workflow. See F1.
The inspected search implementation works in memory over visible document candidates. It does not call Elasticsearch or another remote search engine. OCR and summary fields are searched when present; a field's existence does not demonstrate a processing pipeline.
Follow the collection pipeline
SearchServiceImpl.search validates page/size, normalizes query terms, resolves actor membership, and asks persistence for visible documents. It combines title, OCR content, and summary into searchable text. mapNotNull omits non-matches; each matching result gets a score equal to the number of matched terms. Results are sorted, then sliced into a PageImpl.
Matching uses containment, with an optional edit-distance fallback for words longer than two characters. The fuzzy path accepts Levenshtein distance at most one. An empty normalized query produces no matched terms and therefore no results. Read the code instead of importing expectations from a commercial search engine.
Collection elegance has costs
The operations are easy to follow, but fetch all visible candidates before pagination. A page size of 20 does not mean only 20 documents were loaded or scored. Repeated tokenization and edit-distance calculations also cost CPU. Measure candidate count and input length before deciding which step to optimize.
The highlight builder inserts <em> markers into snippets. That is a presentation contract, not an automatic guarantee of HTML safety. A consuming UI must treat document content as untrusted and render/sanitize appropriately. The frontend implementation is outside this course.
Design a future search ACL
As an exercise, introduce a domain-facing DocumentSearch port whose result contains document IDs, scores, and structured highlight ranges. An external-engine adapter would translate vendor query syntax, result scores, pagination, and failures into that contract. This is a stronger example of semantic anti-corruption across systems than simply renaming fields.
Decide how permission changes reach the index and how to prevent stale-index disclosure. Define authoritative access checks and pagination behavior after filtering. Replacing the in-memory loop without those decisions can change visible behavior or expose data.
Practice
Trace one exact match, one typo match, and one no-match through the actual code. Compute the score by hand. Add boundary cases for page/size and empty query in a practice checkout. Draft a comparison of the existing implementation and the proposed search port, marking each proposed behavior explicitly.
Verification gate
Explain why pagination does not bound candidate loading here. Distinguish database-backed candidate filtering from in-memory ranking. Describe the translation and consistency responsibilities of an external search adapter without claiming it is already implemented.
Read the implementation
Complete source walkthrough
Read these pinned files alongside the explanation above. These are the inspected implementation, not the capstone solution.
SearchServiceImpl.kt
package at.fhtw.swen3.paperless.search.service
import at.fhtw.swen3.paperless.auth.model.AuthenticatedPrincipal
import at.fhtw.swen3.paperless.document.model.Document
import at.fhtw.swen3.paperless.document.persistence.DocumentPersistence
import at.fhtw.swen3.paperless.search.model.SearchResult
import at.fhtw.swen3.paperless.team.persistence.TeamMemberPersistence
import jakarta.validation.ConstraintViolationException
import org.slf4j.LoggerFactory
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageImpl
import org.springframework.data.domain.PageRequest
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
@Transactional(readOnly = true)
class SearchServiceImpl(
private val documentRepository: DocumentPersistence,
private val teamMemberRepository: TeamMemberPersistence
) : SearchService {
private val log = LoggerFactory.getLogger(javaClass)
override fun search(query: String, fuzzy: Boolean, page: Int, size: Int): Page<SearchResult> {
if (page < 0) throw ConstraintViolationException("page must be non-negative", emptySet())
if (size !in 1..100) throw ConstraintViolationException("size must be between 1 and 100", emptySet())
val terms = query.trim().lowercase().split(Regex("\\s+")).filter(String::isNotBlank)
val actorId = AuthenticatedPrincipal.userId(SecurityContextHolder.getContext().authentication?.name)
val teamIds = teamMemberRepository.findByUserId(actorId).mapTo(mutableSetOf()) { requireNotNull(it.team.id) }
val documents = if (teamIds.isEmpty()) {
documentRepository.findOwnerOnlyDocuments(actorId)
} else {
documentRepository.findVisibleDocuments(actorId, teamIds)
}
val results = documents.mapNotNull { document ->
val searchable = listOfNotNull(document.title, document.ocrContent, document.summary)
.joinToString(" ").lowercase()
val matched = terms.filter { term ->
searchable.contains(term) || (fuzzy && searchable.split(Regex("\\W+")).any { fuzzyMatch(term, it) })
}
if (matched.isEmpty()) null else SearchResult(document, matched.size.toFloat(), highlights(document, matched))
}.sortedByDescending(SearchResult::score)
val request = PageRequest.of(page, size)
val from = minOf(page.toLong() * size, results.size.toLong()).toInt()
val to = minOf(from.toLong() + size, results.size.toLong()).toInt()
log.debug("[SEARCH] - ACTION: search: page: {}, size: {}, resultCount: {}", page, size, results.size)
return PageImpl(results.subList(from, to), request, results.size.toLong())
}
private fun fuzzyMatch(term: String, word: String): Boolean =
term.length > 2 && word.length > 2 && levenshtein(term, word) <= 1
private fun levenshtein(left: String, right: String): Int {
var previous = IntArray(right.length + 1) { it }
for (i in left.indices) {
val current = IntArray(right.length + 1)
current[0] = i + 1
for (j in right.indices) {
current[j + 1] = minOf(
current[j] + 1,
previous[j + 1] + 1,
previous[j] + if (left[i] == right[j]) 0 else 1
)
}
previous = current
}
return previous[right.length]
}
private fun highlights(
document: Document,
terms: List<String>
): List<String> = listOfNotNull(document.title, document.ocrContent, document.summary)
.flatMap { text ->
terms.fold(listOf(text)) { snippets, term ->
snippets.map { it.replace(Regex("(?i)\\b${Regex.escape(term)}\\b"), "<em>$term</em>") }
}
}
.filter { it.contains("<em>") }
.take(3)
}
SearchResult.kt
package at.fhtw.swen3.paperless.search.model
import at.fhtw.swen3.paperless.document.model.Document
data class SearchResult(
val document: Document,
val score: Float,
val highlights: List<String> = emptyList()
)
SearchMapper.kt
package at.fhtw.swen3.paperless.search.mapper
import at.fhtw.swen3.paperless.common.mapper.MappingConverters
import at.fhtw.swen3.paperless.document.mapper.DocumentMapper
import at.fhtw.swen3.paperless.dto.SearchResultItem
import at.fhtw.swen3.paperless.search.model.SearchResult
import org.mapstruct.InjectionStrategy
import org.mapstruct.Mapper
import org.mapstruct.Mapping
import org.mapstruct.MappingConstants
import org.mapstruct.Named
import org.mapstruct.ReportingPolicy
@Mapper(
componentModel = MappingConstants.ComponentModel.SPRING,
injectionStrategy = InjectionStrategy.CONSTRUCTOR,
uses = [MappingConverters::class, DocumentMapper::class],
unmappedTargetPolicy = ReportingPolicy.ERROR
)
interface SearchMapper {
@Mapping(target = "highlights", source = "highlights", qualifiedByName = ["nullIfEmpty"])
fun toDto(result: SearchResult): SearchResultItem
@Named("nullIfEmpty")
fun nullIfEmpty(highlights: List<String>?): List<String>? =
if (highlights.isNullOrEmpty()) null else highlights
}
SearchServiceImplTest.kt
package at.fhtw.swen3.paperless.search.service
import at.fhtw.swen3.paperless.document.model.Document
import at.fhtw.swen3.paperless.document.model.ProcessingStatus
import at.fhtw.swen3.paperless.document.persistence.DocumentPersistence
import at.fhtw.swen3.paperless.exception.AuthenticationRequiredException
import at.fhtw.swen3.paperless.team.model.Role
import at.fhtw.swen3.paperless.team.model.Team
import at.fhtw.swen3.paperless.team.model.TeamMember
import at.fhtw.swen3.paperless.team.persistence.TeamMemberPersistence
import at.fhtw.swen3.paperless.user.model.User
import jakarta.validation.ConstraintViolationException
import java.time.Instant
import java.util.UUID
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertAll
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.Mockito.verify
import org.mockito.Mockito.verifyNoInteractions
import org.mockito.junit.jupiter.MockitoExtension
import org.springframework.security.authentication.TestingAuthenticationToken
import org.springframework.security.core.context.SecurityContextHolder
@ExtendWith(MockitoExtension::class)
class SearchServiceImplTest {
@Mock
lateinit var documentRepository: DocumentPersistence
@Mock
lateinit var teamMemberRepository: TeamMemberPersistence
@InjectMocks
lateinit var service: SearchServiceImpl
@BeforeEach
fun set_actor() {
SecurityContextHolder.getContext().authentication = TestingAuthenticationToken(uuid(1).toString(), null)
}
@AfterEach
fun clear_actor() = SecurityContextHolder.clearContext()
@Test
fun search_multi_term_and_pagination_ok() {
// given
`when`(documentRepository.findOwnerOnlyDocuments(uuid(1))).thenReturn(
listOf(
document(uuid(1), "Invoice", "Invoice from Acme"),
document(uuid(2), "Invoice", "Invoice from another sender")
)
)
// when
val firstPage = service.search("invoice acme", false, 0, 1)
val secondPage = service.search("invoice acme", false, 1, 1)
// then
assertAll(
{ assertThat(firstPage.totalElements).isEqualTo(2) },
{ assertThat(firstPage.content.single().document.id).isEqualTo(uuid(1)) },
{ assertThat(firstPage.content.single().score).isEqualTo(2.0f) },
{
assertThat(firstPage.content.single().highlights).containsExactly(
"<em>invoice</em>",
"<em>invoice</em> from <em>acme</em>",
"An <em>invoice</em>"
)
},
{ assertThat(secondPage.content.single().document.id).isEqualTo(uuid(2)) }
)
}
@Test
fun search_fuzzy_terms_ok() {
// given
`when`(documentRepository.findOwnerOnlyDocuments(uuid(1))).thenReturn(listOf(document(uuid(1), "Invoice", "Invoice from Acme")))
// when
val result = service.search("invoic acm", true, 0, 10)
// then
assertAll(
{ assertThat(result.totalElements).isEqualTo(1) },
{ assertThat(result.content.single().score).isEqualTo(2.0f) }
)
}
@Test
fun search_without_matches_returns_empty_page_ok() {
// given
`when`(documentRepository.findOwnerOnlyDocuments(uuid(1))).thenReturn(listOf(document(uuid(1), "Invoice", "Invoice from Acme")))
// when
val result = service.search("passport", false, 0, 10)
// then
assertThat(result).isEmpty()
}
@Test
fun search_does_not_expose_candidates_excluded_by_visibility_boundary() {
// given
val hiddenCandidate = document(uuid(2), "Secret report", "project-aurora")
`when`(documentRepository.findOwnerOnlyDocuments(uuid(1))).thenReturn(
listOf(document(uuid(1), "Invoice", "Invoice from Acme"))
)
// when
val result = service.search(hiddenCandidate.ocrContent!!, false, 0, 10)
// then
assertAll(
{ assertThat(result.content).isEmpty() },
{ assertThat(result.totalElements).isZero() },
{ assertThat(result.content.flatMap { it.highlights }).isEmpty() }
)
verify(documentRepository).findOwnerOnlyDocuments(uuid(1))
}
@Test
fun search_with_maximum_page_returns_empty_page_without_overflow() {
// given
`when`(documentRepository.findOwnerOnlyDocuments(uuid(1))).thenReturn(listOf(document(uuid(1), "Invoice", "Invoice from Acme")))
// when
val result = service.search("invoice", false, Int.MAX_VALUE, 100)
// then
assertAll(
{ assertThat(result.content).isEmpty() },
{ assertThat(result.totalElements).isEqualTo(1) }
)
}
@Test
fun search_rejects_negative_page() {
assertThrows<ConstraintViolationException> {
service.search("invoice", false, -1, 10)
}
verifyNoInteractions(documentRepository, teamMemberRepository)
}
@Test
fun search_rejects_zero_size() {
assertThrows<ConstraintViolationException> {
service.search("invoice", false, 0, 0)
}
verifyNoInteractions(documentRepository, teamMemberRepository)
}
@Test
fun search_rejects_size_above_maximum() {
assertThrows<ConstraintViolationException> {
service.search("invoice", false, 0, 101)
}
verifyNoInteractions(documentRepository, teamMemberRepository)
}
@Test
fun team_search_uses_current_memberships_to_select_candidates_ok() {
// given
val membership = TeamMember(
Team(uuid(4), "Team", null, Instant.EPOCH, null),
User(uuid(1), "alice", "unused", Instant.EPOCH, null), Role.READONLY, Instant.EPOCH
)
`when`(teamMemberRepository.findByUserId(uuid(1))).thenReturn(listOf(membership))
`when`(documentRepository.findVisibleDocuments(uuid(1), setOf(uuid(4))))
.thenReturn(listOf(document(uuid(3), "Invoice", "Invoice from Acme").copy(teamId = uuid(4))))
// when
val result = service.search("invoice", false, 0, 10)
// then
assertThat(result.content.single().document.teamId).isEqualTo(uuid(4))
verify(documentRepository).findVisibleDocuments(uuid(1), setOf(uuid(4)))
}
@Test
fun malformed_principal_fails_before_loading_candidates_ko() {
// given
SecurityContextHolder.getContext().authentication = TestingAuthenticationToken("not-a-uuid", null)
// when / then
assertThrows<AuthenticationRequiredException> { service.search("invoice", false, 0, 10) }
verifyNoInteractions(documentRepository, teamMemberRepository)
}
private fun uuid(value: Int) = UUID(0L, value.toLong())
private fun document(id: UUID, title: String, text: String) = Document(
id = id,
title = title,
originalFilename = "document.pdf",
contentType = "application/pdf",
fileSize = 10,
status = ProcessingStatus.COMPLETED,
ocrContent = text,
summary = "An invoice",
storageKey = null,
documentType = null,
createdAt = Instant.EPOCH,
updatedAt = Instant.EPOCH,
ownerId = uuid(1)
)
}