Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/main/java/cz/cvut/kbss/termit/dto/VocabularyDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ public VocabularyDto(Vocabulary source) {
setLabel(source.getLabel());
setDescription(source.getDescription());
setPrimaryLanguage(source.getPrimaryLanguage());
setPreferredNamespaceUri(source.getPreferredNamespaceUri());
setPreferredNamespacePrefix(source.getPreferredNamespacePrefix());
setDocument(source.getDocument());
setImportedVocabularies(source.getImportedVocabularies());
setRelatedVocabularies(source.getRelatedVocabularies());
Expand Down
22 changes: 22 additions & 0 deletions src/main/java/cz/cvut/kbss/termit/model/Vocabulary.java
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,12 @@ public class Vocabulary extends Asset<MultilingualString>
@OWLAnnotationProperty(iri = DC.Terms.LANGUAGE, simpleLiteral = true)
private String primaryLanguage;

@OWLAnnotationProperty(iri = cz.cvut.kbss.termit.util.Vocabulary.s_p_preferredNamespaceUri, simpleLiteral = true)
private String preferredNamespaceUri;

@OWLAnnotationProperty(iri = cz.cvut.kbss.termit.util.Vocabulary.s_p_preferredNamespacePrefix, simpleLiteral = true)
private String preferredNamespacePrefix;

@OWLObjectProperty(iri = cz.cvut.kbss.termit.util.Vocabulary.s_p_imports_vocabulary)
private Set<URI> importedVocabularies;

Expand Down Expand Up @@ -147,6 +153,22 @@ public void setPrimaryLanguage(String primaryLanguage) {
this.primaryLanguage = primaryLanguage;
}

public String getPreferredNamespaceUri() {
return preferredNamespaceUri;
}

public void setPreferredNamespaceUri(String preferredNamespaceUri) {
this.preferredNamespaceUri = preferredNamespaceUri;
}

public String getPreferredNamespacePrefix() {
return preferredNamespacePrefix;
}

public void setPreferredNamespacePrefix(String preferredNamespacePrefix) {
this.preferredNamespacePrefix = preferredNamespacePrefix;
}

@Override
public String getPrimaryLabel() {
return getLabel(getPrimaryLanguage());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -428,8 +428,6 @@ public Optional<Vocabulary> findVersionValidAt(Vocabulary vocabulary, Instant at

/**
* Resolves preferred namespace prefix and URI of a vocabulary with the specified identifier.
* <p>
* This method expects that the prefix and namespace are declared on the vocabulary itself, not on its glossary.
*
* @param vocabularyUri Vocabulary identifier
* @return Prefix declaration, possibly containing {@code null} values
Expand All @@ -449,9 +447,9 @@ public PrefixDeclaration resolvePrefix(URI vocabularyUri) {
if (result.isEmpty()) {
return PrefixDeclaration.EMPTY_PREFIX;
}
assert result.get(0) instanceof Object[];
return new PrefixDeclaration(((Object[]) result.get(0))[0].toString(),
((Object[]) result.get(0))[1].toString());
assert result.getFirst() instanceof Object[];
return new PrefixDeclaration(((Object[]) result.getFirst())[0].toString(),
((Object[]) result.getFirst())[1].toString());
} catch (RuntimeException e) {
throw new PersistenceException(e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,6 @@ public class SKOSImporter implements VocabularyImporter {

private final ValueFactory vf = SimpleValueFactory.getInstance();

private String namespace;
private IRI vocabularyIri;

@Autowired
Expand Down Expand Up @@ -145,7 +144,6 @@ private Vocabulary importVocabulary(final boolean rename,
validateRequiredLanguageTags();

this.vocabularyIri = resolveVocabularyIriFromImportedData();
this.namespace = resolveVocabularyNamespaceFromData();
LOG.trace("Importing vocabulary {}.", this.vocabularyIri);
removeTopConceptOfAssertions();
insertHasTopConceptAssertions();
Expand Down Expand Up @@ -237,11 +235,7 @@ private void clearVocabulary(Vocabulary newVocabulary) {
}

private void ensureConceptIrisAreCompatibleWithTermIt(Vocabulary vocabulary) {
assert vocabulary.getProperties()
.getOrDefault(cz.cvut.kbss.termit.util.Vocabulary.s_p_preferredNamespaceUri, Set.of())
.size() == 1;
final String ns = vocabulary.getProperties().get(cz.cvut.kbss.termit.util.Vocabulary.s_p_preferredNamespaceUri)
.iterator().next().toString();
final String ns = vocabulary.getPreferredNamespaceUri();
final char separator = ns.charAt(ns.length() - 1);
final Statement[] statements = model.filter(null, RDF.TYPE, SKOS.CONCEPT).toArray(new Statement[]{});
for (final Statement c : statements) {
Expand Down Expand Up @@ -387,7 +381,7 @@ private void setVocabularyPrimaryLanguage(Vocabulary vocabulary) {
if (!languageSet) {
AtomicReference<MultilingualString> labelRef = new AtomicReference<>();
handleStringStringProperty(vocabularyIri, DCTERMS.TITLE, labelRef::set, config.getPersistence()
.getLanguage());
.getLanguage());
MultilingualString label = labelRef.get();
if (label == null || label.isEmpty() || label.contains(config.getPersistence().getLanguage())) {
vocabulary.setPrimaryLanguage(config.getPersistence().getLanguage());
Expand All @@ -398,9 +392,9 @@ private void setVocabularyPrimaryLanguage(Vocabulary vocabulary) {
}

/**
* Looks up the language property in the vocabulary and/or glossary and sets it as the primary language.
* Looks up {@literal dcterms:language} in the glossary, loads the first value as string and passes it to the
* provided consumer.
* Looks up the language property in the vocabulary and/or glossary and sets it as the primary language. Looks up
* {@literal dcterms:language} in the glossary, loads the first value as string and passes it to the provided
* consumer.
*
* @param consumer Consumer to accept the literal string value if found
* @return true if the property was found and the consumer was called, false otherwise
Expand Down Expand Up @@ -467,15 +461,18 @@ private void setVocabularyDescription(Vocabulary vocabulary) {
}

private void setVocabularyNamespaceInfoFromData(Vocabulary vocabulary) {
namespaceResolver.setVocabularyPreferredNamespace(vocabulary, namespace);
namespaceResolver.setVocabularyPreferredNamespace(vocabulary, resolveVocabularyNamespaceFromData());
// Remove namespace URI declaration from model, it will be added with Vocabulary
model.removeAll(model.filter(null, vf.createIRI(
cz.cvut.kbss.termit.util.Vocabulary.s_p_preferredNamespaceUri), null));
final Model prefixModel = model.filter(null, vf.createIRI(
cz.cvut.kbss.termit.util.Vocabulary.s_p_preferredNamespacePrefix), null);
prefixModel.forEach(s -> {
final String prefix = s.getObject().stringValue();
if (!prefixModel.isEmpty()) {
final String prefix = prefixModel.iterator().next().getObject().stringValue();
LOG.trace("Found preferred namespace prefix: {}", prefix);
vocabulary.addUnmappedPropertyValue(cz.cvut.kbss.termit.util.Vocabulary.s_p_preferredNamespacePrefix,
prefix);
});
vocabulary.setPreferredNamespacePrefix(prefix);
model.removeAll(prefixModel);
}
}

private void notifyReferencingTerms() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import cz.cvut.kbss.termit.persistence.dao.VocabularyDao;
import cz.cvut.kbss.termit.service.IdentifierResolver;
import cz.cvut.kbss.termit.util.Configuration;
import cz.cvut.kbss.termit.util.Utils;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
import org.springframework.cache.annotation.CacheConfig;
Expand Down Expand Up @@ -36,7 +37,19 @@ public VocabularyNamespaceResolver(VocabularyDao vocabularyDao, Configuration co
public String resolveNamespace(@Nonnull URI vocabularyUri) {
Objects.requireNonNull(vocabularyUri);
return vocabularyDao.getPreferredNamespace(vocabularyUri)
.orElseGet(() -> vocabularyUri + namespaceConfig.getSeparator());
.orElseGet(() -> generateNamespace(vocabularyUri.toString()));
}

/**
* Generates vocabulary namespace using the specified identifier and the configured term namespace separator.
*
* @param vocabularyUri Vocabulary identifier
* @return Generated namespace
*/
@Nonnull
public String generateNamespace(@Nonnull String vocabularyUri) {
Objects.requireNonNull(vocabularyUri);
return vocabularyUri + IdentifierResolver.ensureNamespaceSeparatorTermination(namespaceConfig.getSeparator());
}

/**
Expand All @@ -54,11 +67,10 @@ public void setVocabularyPreferredNamespace(@Nonnull Vocabulary vocabulary) {
if (vocabulary.getUri() == null) {
throw new IllegalArgumentException("Vocabulary " + vocabulary + " is missing identifier.");
}
if (!vocabulary.hasUnmappedPropertyValue(cz.cvut.kbss.termit.util.Vocabulary.s_p_preferredNamespaceUri)) {
if (Utils.isBlank(vocabulary.getPreferredNamespaceUri())) {
String configuredSep = namespaceConfig.getSeparator();
vocabulary.addUnmappedPropertyValue(cz.cvut.kbss.termit.util.Vocabulary.s_p_preferredNamespaceUri,
IdentifierResolver.ensureNamespaceSeparatorTermination(
vocabulary.getUri() + configuredSep));
vocabulary.setPreferredNamespaceUri(IdentifierResolver.ensureNamespaceSeparatorTermination(
vocabulary.getUri() + configuredSep));
}
}

Expand All @@ -75,10 +87,8 @@ public void setVocabularyPreferredNamespace(@Nonnull Vocabulary vocabulary) {
*/
public void setVocabularyPreferredNamespace(@Nonnull Vocabulary vocabulary, @Nullable String namespace) {
Objects.requireNonNull(vocabulary);
if (namespace != null && !vocabulary.hasUnmappedPropertyValue(
cz.cvut.kbss.termit.util.Vocabulary.s_p_preferredNamespaceUri)) {
vocabulary.addUnmappedPropertyValue(cz.cvut.kbss.termit.util.Vocabulary.s_p_preferredNamespaceUri,
namespace);
if (namespace != null && Utils.isBlank(vocabulary.getPreferredNamespaceUri())) {
vocabulary.setPreferredNamespaceUri(namespace);
} else {
setVocabularyPreferredNamespace(vocabulary);
}
Expand Down
13 changes: 12 additions & 1 deletion src/main/java/cz/cvut/kbss/termit/rest/IdentifierController.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@
package cz.cvut.kbss.termit.rest;

import cz.cvut.kbss.termit.exception.InvalidParameterException;
import cz.cvut.kbss.termit.persistence.namespace.VocabularyNamespaceResolver;
import cz.cvut.kbss.termit.rest.dto.AssetType;
import cz.cvut.kbss.termit.security.SecurityConstants;
import cz.cvut.kbss.termit.service.IdentifierResolver;
import cz.cvut.kbss.termit.persistence.namespace.VocabularyNamespaceResolver;
import cz.cvut.kbss.termit.util.Configuration;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
Expand Down Expand Up @@ -110,4 +110,15 @@ private static void ensureContextIriIsNotNull(AssetType assetType, String contex
throw new InvalidParameterException("ContextIri must be supplied for asset of type " + assetType);
}
}

@Operation(
description = "Returns namespace which would be generated by the application for the specified vocabulary identifier (using the configured term identifier separator).")
@ApiResponse(responseCode = "200", description = "Generated namespace.")
@PreAuthorize("permitAll()")
@PostMapping(value = "/namespace")
public String generateVocabularyNamespace(@Parameter(
description = "IRI to use as context for identifier generation. For example, for a term it would the vocabulary IRI.")
@RequestParam(value = "vocabularyIri") String vocabularyIri) {
return vocabularyNamespaceResolver.generateNamespace(vocabularyIri);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,8 @@ protected void preUpdate(@Nonnull Vocabulary instance) {
verifyVocabularyImports(instance, original);
// ACL reference does not change, but it can be missing in case the instance arrived from client
instance.setAcl(original.getAcl());
// Preferred namespace URI must not change, it would break term IRI resolution
instance.setPreferredNamespaceUri(original.getPreferredNamespaceUri());
// Client does not get root terms, restore them from the original instance
instance.setRootTerms(original.getRootTerms());
SnapshotProvider.verifySnapshotNotModified(original);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ void updateEvictsPossiblyPreviouslyLoadedInstanceFromSecondLevelCache() {
transactional(() -> sut.update(vocabulary));
final List<Vocabulary> result = sut.findAll();
assertEquals(1, result.size());
assertEquals(newName, result.get(0).getLabel().get(Environment.LANGUAGE));
assertEquals(newName, result.getFirst().getLabel().get(Environment.LANGUAGE));
}

@Test
Expand Down Expand Up @@ -595,10 +595,8 @@ void resolvePrefixRetrievesPrefixDeclarationForVocabulary() {
vocabulary.setProperties(new HashMap<>());
final String prefix = "vocab";
final String namespace = SKOS.CONCEPT_SCHEME + "/";
vocabulary.getProperties().put(cz.cvut.kbss.termit.util.Vocabulary.s_p_preferredNamespacePrefix,
Collections.singleton(prefix));
vocabulary.getProperties().put(cz.cvut.kbss.termit.util.Vocabulary.s_p_preferredNamespaceUri,
Collections.singleton(namespace));
vocabulary.setPreferredNamespaceUri(namespace);
vocabulary.setPreferredNamespacePrefix(prefix);
transactional(() -> em.persist(vocabulary, descriptorFor(vocabulary)));

final PrefixDeclaration result = sut.resolvePrefix(vocabulary.getUri());
Expand Down Expand Up @@ -750,7 +748,7 @@ void getAnyExternalRelationsReturnsTermsWithIncomingRelations(URI termRelation)
final List<RdfStatement> relations = sut.getIncomingTermRelations(vocabulary);

assertEquals(1, relations.size());
final RdfStatement relation = relations.get(0);
final RdfStatement relation = relations.getFirst();
assertEquals(secondTerm.getUri(), relation.getSubject());
assertEquals(termRelation, relation.getRelation());
assertEquals(term.getUri(), relation.getObject());
Expand Down Expand Up @@ -810,7 +808,7 @@ void getPrimaryLanguageReturnsThePrimaryLanguageOfTheVocabulary() {
void getPreferredNamespaceReturnsStoredVocabularyNamespace() {
final Vocabulary vocabulary = Generator.generateVocabularyWithId();
final String namespace = vocabulary.getUri().toString().substring(0, vocabulary.getUri().toString().lastIndexOf('/') + 1);
vocabulary.setProperties(Map.of(cz.cvut.kbss.termit.util.Vocabulary.s_p_preferredNamespaceUri, Set.of(namespace)));
vocabulary.setPreferredNamespaceUri(namespace);
final Descriptor descriptor = descriptorFactory.vocabularyDescriptor(vocabulary);
transactional(() -> em.persist(vocabulary, descriptor));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,8 @@ void importGeneratesRelationshipsBetweenTermsAndVocabulary() {
.map(Statement::getSubject).toList();
assertFalse(terms.isEmpty());
terms.forEach(t -> {
final List<Statement> inScheme = conn.getStatements(t, SKOS.IN_SCHEME, vf.createIRI(VOCABULARY_IRI_S))
final List<Statement> inScheme = conn.getStatements(t, SKOS.IN_SCHEME,
vf.createIRI(VOCABULARY_IRI_S))
.stream().toList();
assertFalse(inScheme.isEmpty());
});
Expand Down Expand Up @@ -530,10 +531,7 @@ void importVocabularyUsesPreferredNamespaceFromImportedData() {

final cz.cvut.kbss.termit.model.Vocabulary result = findVocabulary();
assertNotNull(result);
assertThat(result.getProperties().keySet(),
hasItem(cz.cvut.kbss.termit.util.Vocabulary.s_p_preferredNamespaceUri));
assertEquals(Set.of("http://onto.fel.cvut.cz/ontologies/application/termit/"),
result.getProperties().get(cz.cvut.kbss.termit.util.Vocabulary.s_p_preferredNamespaceUri));
assertEquals("http://onto.fel.cvut.cz/ontologies/application/termit/", result.getPreferredNamespaceUri());
}

@Test
Expand Down
Loading