Skip to content

Commit

Permalink
[Enhancement kbss-cvut/termit-ui#528] Change TermDao#resolveVocabular…
Browse files Browse the repository at this point in the history
…yId to return optional URI instead of throwing when term is not found (not in a vocabulary).
  • Loading branch information
lukaskabc committed Nov 14, 2024
1 parent edfbbe5 commit ca0af58
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
12 changes: 6 additions & 6 deletions src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -91,23 +91,23 @@ protected URI labelProperty() {
@Override
public Optional<Term> find(URI id) {
try {
final Optional<Term> result = Optional.ofNullable(
em.find(Term.class, id, descriptorFactory.termDescriptor(resolveVocabularyId(id))));
final Optional<Term> result = resolveVocabularyId(id).map(vocabulary ->
em.find(Term.class, id, descriptorFactory.termDescriptor(vocabulary)));
result.ifPresent(this::postLoad);
return result;
} catch (RuntimeException e) {
throw new PersistenceException(e);
}
}

private URI resolveVocabularyId(URI termId) {
private Optional<URI> resolveVocabularyId(URI termId) {
try {
return em.createNativeQuery("SELECT DISTINCT ?v WHERE { ?t ?inVocabulary ?v . }", URI.class)
return Optional.of(em.createNativeQuery("SELECT DISTINCT ?v WHERE { ?t ?inVocabulary ?v . }", URI.class)
.setParameter("t", termId)
.setParameter("inVocabulary", TERM_FROM_VOCABULARY)
.getSingleResult();
.getSingleResult());
} catch (NoResultException | NoUniqueResultException e) {
throw new PersistenceException("Unable to resolve term vocabulary.", e);
return Optional.empty();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
Expand Down Expand Up @@ -1394,4 +1395,12 @@ void findByIdLoadsTermFromVocabularyContextOnly() {
assertTrue(result.isPresent());
assertFalse(result.get().getProperties().containsKey(property));
}

@Test
void findByIdReturnsOptionalEmptyWhenTermDoesNotExists() {
final Term term = Generator.generateTermWithId(vocabulary.getUri());
// trying to find a non-existing term
final Optional<Term> empty = assertDoesNotThrow(()-> sut.find(term.getUri()));
assertTrue(empty.isEmpty());
}
}

0 comments on commit ca0af58

Please sign in to comment.