use of com.b2international.snowowl.core.request.BranchRequest in project snow-owl by b2ihealthcare.
the class CodeSystemUpgradeSynchronizationRequest method execute.
@Override
public Boolean execute(RepositoryContext context) {
final String message = String.format("Merge %s into %s", source, codeSystemId);
CodeSystem codeSystem = CodeSystemRequests.prepareGetCodeSystem(codeSystemId.getResourceId()).build().execute(context);
if (codeSystem.getUpgradeOf() == null) {
throw new BadRequestException("Code System '%s' is not an Upgrade Code System. It cannot be synchronized with '%s'.", codeSystemId, source);
}
final String sourceBranchPath = context.service(ResourceURIPathResolver.class).resolve(context, List.of(source)).stream().findFirst().get();
// merge all changes from the source to the current upgrade of branch
final Merge merge = RepositoryRequests.merging().prepareCreate().setSource(sourceBranchPath).setTarget(codeSystem.getBranchPath()).setUserId(context.service(User.class).getUsername()).setCommitComment(message).setSquash(false).build(codeSystem.getToolingId()).getRequest().execute(context);
if (merge.getStatus() != Merge.Status.COMPLETED) {
// report conflicts
ApiError apiError = merge.getApiError();
Collection<MergeConflict> conflicts = merge.getConflicts();
context.log().error("Failed to sync source CodeSystem content to upgrade CodeSystem. Error: {}. Conflicts: {}", apiError.getMessage(), conflicts);
throw new ConflictException("Upgrade code system synchronization can not be performed due to conflicting content errors.").withAdditionalInfo(Map.of("conflicts", conflicts, "mergeError", apiError.getMessage()));
}
if (!codeSystem.getUpgradeOf().equals(source)) {
return new BranchRequest<>(Branch.MAIN_PATH, new ResourceRepositoryCommitRequestBuilder().setBody((tx) -> {
ResourceDocument entry = tx.lookup(codeSystemId.getResourceId(), ResourceDocument.class);
tx.add(ResourceDocument.builder(entry).upgradeOf(source).build());
tx.commit(String.format("Update upgradeOf from '%s' to '%s'", codeSystem.getUpgradeOf(), source));
return Boolean.TRUE;
}).setCommitComment(String.format("Complete upgrade of %s to %s", codeSystem.getUpgradeOf().getResourceId(), codeSystem.getExtensionOf())).build()).execute(context).getResultAs(Boolean.class);
} else {
return Boolean.TRUE;
}
}
use of com.b2international.snowowl.core.request.BranchRequest in project snow-owl by b2ihealthcare.
the class DescriptionChangeConverter method expand.
@Override
public void expand(final List<DescriptionChange> results) {
if (!expand().containsKey(DescriptionChange.Expand.DESCRIPTION)) {
return;
}
/*
* Depending on the CD member change search request, we might need to issue
* SNOMED CT searches against multiple branches; find out which ones we have.
*/
final Multimap<String, DescriptionChange> itemsByBranch = getItemsByBranch(results);
// Check if we only need to load inferred CD members in their entirety
final Options expandOptions = expand().getOptions(DescriptionChange.Expand.DESCRIPTION);
final boolean inferredOnly = expandOptions.getBoolean("inferredOnly");
final Options descriptionExpandOptions = expandOptions.getOptions("expand");
final Options conceptOptions = descriptionExpandOptions.getOptions("concept");
final boolean needsConcept = descriptionExpandOptions.keySet().contains("concept");
for (final String branch : itemsByBranch.keySet()) {
final Collection<DescriptionChange> itemsForCurrentBranch = itemsByBranch.get(branch);
/*
* Expand concept on "new" descriptions via a separate search request, they will
* be different from the concept on the "origin" description.
*/
if (needsConcept) {
final List<ReasonerDescription> blankDescriptions = itemsForCurrentBranch.stream().filter(c -> ChangeNature.NEW.equals(c.getChangeNature())).map(DescriptionChange::getDescription).collect(Collectors.toList());
final Multimap<String, ReasonerDescription> descriptionsByConceptId = FluentIterable.from(blankDescriptions).index(ReasonerDescription::getConceptId);
final Set<String> conceptIds = descriptionsByConceptId.keySet();
final Request<BranchContext, SnomedConcepts> conceptSearchRequest = SnomedRequests.prepareSearchConcept().filterByIds(conceptIds).setLimit(conceptIds.size()).setExpand(conceptOptions.get("expand", Options.class)).setLocales(locales()).build();
final SnomedConcepts concepts = new BranchRequest<>(branch, new RevisionIndexReadRequest<>(conceptSearchRequest)).execute(context());
for (final SnomedConcept concept : concepts) {
final String conceptId = concept.getId();
final Collection<ReasonerDescription> descriptionsForConcept = descriptionsByConceptId.get(conceptId);
for (final ReasonerDescription description : descriptionsForConcept) {
description.setConcept(concept);
}
}
}
/*
* Then fetch all the required descriptions. Note that the same "origin"
* description might be used for multiple eg. "new" counterparts.
*/
final Set<String> descriptionIds = itemsForCurrentBranch.stream().filter(c -> !inferredOnly || ChangeNature.NEW.equals(c.getChangeNature())).map(c -> c.getDescription().getOriginDescriptionId()).collect(Collectors.toSet());
final Request<BranchContext, SnomedDescriptions> descriptionSearchRequest = SnomedRequests.prepareSearchDescription().filterByIds(descriptionIds).setLimit(descriptionIds.size()).setExpand(descriptionExpandOptions).setLocales(locales()).build();
final SnomedDescriptions descriptions = new BranchRequest<>(branch, new RevisionIndexReadRequest<>(descriptionSearchRequest)).execute(context());
final Map<String, SnomedDescription> descriptionsById = Maps.uniqueIndex(descriptions, SnomedDescription::getId);
for (final DescriptionChange item : itemsForCurrentBranch) {
final ReasonerDescription reasonerDescription = item.getDescription();
final String descriptionId = reasonerDescription.getOriginDescriptionId();
switch(item.getChangeNature()) {
case NEW:
{
final SnomedDescription expandedDescription = descriptionsById.get(descriptionId);
reasonerDescription.setAcceptabilityMap(expandedDescription.getAcceptabilityMap());
reasonerDescription.setCaseSignificanceId(expandedDescription.getCaseSignificanceId());
// reasonerDescription.setConcept(...) is already set earlier (or expanded)
reasonerDescription.setLanguageCode(expandedDescription.getLanguageCode());
// reasonerMember.setReleased(...) is already set
reasonerDescription.setTerm(expandedDescription.getTerm());
reasonerDescription.setType(expandedDescription.getType());
}
break;
case REDUNDANT:
if (!inferredOnly) {
final SnomedDescription expandedDescription = descriptionsById.get(descriptionId);
reasonerDescription.setAcceptabilityMap(expandedDescription.getAcceptabilityMap());
reasonerDescription.setCaseSignificanceId(expandedDescription.getCaseSignificanceId());
reasonerDescription.setConcept(expandedDescription.getConcept());
reasonerDescription.setLanguageCode(expandedDescription.getLanguageCode());
// reasonerMember.setReleased(...) is already set
reasonerDescription.setTerm(expandedDescription.getTerm());
reasonerDescription.setType(expandedDescription.getType());
}
break;
default:
throw new IllegalStateException(String.format("Unexpected description change '%s' found with SCTID '%s'.", item.getChangeNature(), item.getDescription().getOriginDescriptionId()));
}
}
}
}
use of com.b2international.snowowl.core.request.BranchRequest in project snow-owl by b2ihealthcare.
the class TerminologyResourceContentRequest method execute.
@Override
public R execute(TerminologyResourceContext context) {
final ResourceURI resourceURI = context.resourceURI();
final TerminologyResource resource = context.resource();
final PathWithVersion branchPathWithVersion = context.service(ResourceURIPathResolver.class).resolveWithVersion(context, resourceURI, resource);
final String path = branchPathWithVersion.getPath();
final ResourceURI versionResourceURI = branchPathWithVersion.getVersionResourceURI();
if (versionResourceURI != null) {
context = context.inject().bind(ResourceURI.class, versionResourceURI).bind(PathWithVersion.class, branchPathWithVersion).build();
}
return new RepositoryRequest<R>(resource.getToolingId(), new BranchRequest<R>(path, next())).execute(context);
}
use of com.b2international.snowowl.core.request.BranchRequest in project snow-owl by b2ihealthcare.
the class SnomedRepositoryPreCommitHook method getChangeSetProcessors.
@Override
protected Collection<ChangeSetProcessor> getChangeSetProcessors(StagingArea staging, RevisionSearcher index) throws IOException {
final RepositoryContext context = ClassUtils.checkAndCast(staging.getContext(), RepositoryContext.class);
// initialize OWL Expression converter on the current branch
final SnomedOWLExpressionConverter expressionConverter = new BranchRequest<>(staging.getBranchPath(), branchContext -> {
return new SnomedOWLExpressionConverter(branchContext.inject().bind(RevisionSearcher.class, index).build());
}).execute(context);
final Set<String> statedSourceIds = Sets.newHashSet();
final Set<String> statedDestinationIds = Sets.newHashSet();
final Set<String> inferredSourceIds = Sets.newHashSet();
final Set<String> inferredDestinationIds = Sets.newHashSet();
collectIds(statedSourceIds, statedDestinationIds, staging.getNewObjects(SnomedRelationshipIndexEntry.class), Concepts.STATED_RELATIONSHIP);
collectIds(statedSourceIds, statedDestinationIds, staging.getChangedRevisions(SnomedRelationshipIndexEntry.class).map(diff -> (SnomedRelationshipIndexEntry) diff.newRevision), Concepts.STATED_RELATIONSHIP);
collectIds(inferredSourceIds, inferredDestinationIds, staging.getNewObjects(SnomedRelationshipIndexEntry.class), Concepts.INFERRED_RELATIONSHIP);
collectIds(inferredSourceIds, inferredDestinationIds, staging.getChangedRevisions(SnomedRelationshipIndexEntry.class).map(diff -> (SnomedRelationshipIndexEntry) diff.newRevision), Concepts.INFERRED_RELATIONSHIP);
collectIds(statedSourceIds, statedDestinationIds, staging.getNewObjects(SnomedRefSetMemberIndexEntry.class), expressionConverter);
collectIds(statedSourceIds, statedDestinationIds, staging.getChangedRevisions(SnomedRefSetMemberIndexEntry.class).map(diff -> (SnomedRefSetMemberIndexEntry) diff.newRevision), expressionConverter);
staging.getRemovedObjects(SnomedRelationshipIndexEntry.class).filter(detachedRelationship -> Concepts.IS_A.equals(detachedRelationship.getTypeId())).forEach(detachedRelationship -> {
// XXX: IS A relationships are expected to have a destination ID, not a value
checkState(!detachedRelationship.hasValue(), "IS A relationship found with value: %s", detachedRelationship.getId());
if (Concepts.STATED_RELATIONSHIP.equals(detachedRelationship.getCharacteristicTypeId())) {
statedSourceIds.add(detachedRelationship.getSourceId());
statedDestinationIds.add(detachedRelationship.getDestinationId());
} else if (Concepts.INFERRED_RELATIONSHIP.equals(detachedRelationship.getCharacteristicTypeId())) {
inferredSourceIds.add(detachedRelationship.getSourceId());
inferredDestinationIds.add(detachedRelationship.getDestinationId());
}
});
staging.getRemovedObjects(SnomedRefSetMemberIndexEntry.class).filter(detachedMember -> SnomedRefSetType.OWL_AXIOM == detachedMember.getReferenceSetType()).forEach(detachedOwlMember -> {
collectIds(statedSourceIds, statedDestinationIds, detachedOwlMember, expressionConverter);
});
final LongSet statedConceptIds = PrimitiveSets.newLongOpenHashSet();
final LongSet inferredConceptIds = PrimitiveSets.newLongOpenHashSet();
if (!statedDestinationIds.isEmpty()) {
for (SnomedConceptDocument statedDestinationConcept : index.get(SnomedConceptDocument.class, statedDestinationIds)) {
statedConceptIds.add(Long.parseLong(statedDestinationConcept.getId()));
if (statedDestinationConcept.getStatedParents() != null) {
statedConceptIds.addAll(statedDestinationConcept.getStatedParents());
}
if (statedDestinationConcept.getStatedAncestors() != null) {
statedConceptIds.addAll(statedDestinationConcept.getStatedAncestors());
}
}
}
if (!inferredDestinationIds.isEmpty()) {
for (SnomedConceptDocument inferredDestinationConcept : index.get(SnomedConceptDocument.class, inferredDestinationIds)) {
inferredConceptIds.add(Long.parseLong(inferredDestinationConcept.getId()));
if (inferredDestinationConcept.getParents() != null) {
inferredConceptIds.addAll(inferredDestinationConcept.getParents());
}
if (inferredDestinationConcept.getAncestors() != null) {
inferredConceptIds.addAll(inferredDestinationConcept.getAncestors());
}
}
}
staging.getRemovedObjects(SnomedDescriptionIndexEntry.class).forEach(removedDescription -> {
if (removedDescription.isFsn() && removedDescription.isActive()) {
statedSourceIds.add(removedDescription.getConceptId());
inferredSourceIds.add(removedDescription.getConceptId());
}
});
staging.getChangedRevisions(SnomedDescriptionIndexEntry.class).filter(diff -> ((SnomedDescriptionIndexEntry) diff.newRevision).isFsn()).filter(diff -> diff.hasRevisionPropertyChanges(ACTIVE_AND_TERM_FIELDS)).forEach(diff -> {
SnomedDescriptionIndexEntry newRevision = (SnomedDescriptionIndexEntry) diff.newRevision;
statedSourceIds.add(newRevision.getConceptId());
inferredSourceIds.add(newRevision.getConceptId());
});
staging.getNewObjects(SnomedDescriptionIndexEntry.class).filter(newDescription -> newDescription.isFsn() && newDescription.isActive()).forEach(newDescription -> {
statedSourceIds.add(newDescription.getConceptId());
inferredSourceIds.add(newDescription.getConceptId());
});
if (!statedSourceIds.isEmpty()) {
final Query<SnomedConceptDocument> statedSourceConceptsQuery = Query.select(SnomedConceptDocument.class).where(Expressions.builder().should(SnomedConceptDocument.Expressions.ids(statedSourceIds)).should(SnomedConceptDocument.Expressions.statedParents(statedSourceIds)).should(SnomedConceptDocument.Expressions.statedAncestors(statedSourceIds)).build()).limit(Integer.MAX_VALUE).build();
for (SnomedConceptDocument statedSourceConcept : index.search(statedSourceConceptsQuery)) {
statedConceptIds.add(Long.parseLong(statedSourceConcept.getId()));
if (statedSourceConcept.getStatedParents() != null) {
statedConceptIds.addAll(statedSourceConcept.getStatedParents());
}
if (statedSourceConcept.getStatedAncestors() != null) {
statedConceptIds.addAll(statedSourceConcept.getStatedAncestors());
}
}
}
if (!inferredSourceIds.isEmpty()) {
final Query<SnomedConceptDocument> inferredSourceConceptsQuery = Query.select(SnomedConceptDocument.class).where(Expressions.builder().should(SnomedConceptDocument.Expressions.ids(inferredSourceIds)).should(SnomedConceptDocument.Expressions.parents(inferredSourceIds)).should(SnomedConceptDocument.Expressions.ancestors(inferredSourceIds)).build()).limit(Integer.MAX_VALUE).build();
for (SnomedConceptDocument inferredSourceConcept : index.search(inferredSourceConceptsQuery)) {
inferredConceptIds.add(Long.parseLong(inferredSourceConcept.getId()));
if (inferredSourceConcept.getParents() != null) {
inferredConceptIds.addAll(inferredSourceConcept.getParents());
}
if (inferredSourceConcept.getAncestors() != null) {
inferredConceptIds.addAll(inferredSourceConcept.getAncestors());
}
}
}
staging.getNewObjects(SnomedConceptDocument.class).forEach(newConcept -> {
long longId = Long.parseLong(newConcept.getId());
statedConceptIds.add(longId);
inferredConceptIds.add(longId);
});
// collect all reactivated concepts for the taxonomy to properly re-register them in the tree even if they don't carry stated/inferred information in this commit, but they have something in the index
staging.getChangedRevisions(SnomedConceptDocument.class, Set.of(SnomedRf2Headers.FIELD_ACTIVE)).forEach(diff -> {
RevisionPropertyDiff propertyDiff = diff.getRevisionPropertyDiff(SnomedRf2Headers.FIELD_ACTIVE);
if ("false".equals(propertyDiff.getOldValue()) && "true".equals(propertyDiff.getNewValue())) {
long longId = Long.parseLong(diff.newRevision.getId());
statedConceptIds.add(longId);
inferredConceptIds.add(longId);
}
});
log.trace("Retrieving taxonomic information from store...");
final boolean checkCycles = !(context instanceof Rf2TransactionContext);
final Taxonomy inferredTaxonomy = Taxonomies.inferred(index, expressionConverter, staging, inferredConceptIds, checkCycles);
final Taxonomy statedTaxonomy = Taxonomies.stated(index, expressionConverter, staging, statedConceptIds, checkCycles);
// XXX change processor execution order is important!!!
return List.of(// those values will be used in the ConceptChangeProcessor for example to properly compute the preferredDescriptions derived field
new DescriptionChangeProcessor(), new ConceptChangeProcessor(DoiDataProvider.INSTANCE, SnomedIconProvider.INSTANCE.getAvailableIconIds(), statedTaxonomy, inferredTaxonomy), new RelationshipChangeProcessor());
}
use of com.b2international.snowowl.core.request.BranchRequest in project snow-owl by b2ihealthcare.
the class Rf2Exporter method exportBranch.
public final void exportBranch(final Path releaseDirectory, final RepositoryContext context, final String branch, final long effectiveTimeStart, final long effectiveTimeEnd, final Set<String> visitedComponentEffectiveTimes) throws IOException {
LOG.info("Exporting {} branch to '{}'", branch, getFileName());
// Ensure that the path leading to the export file exists
final Path exportFileDirectory = releaseDirectory.resolve(getRelativeDirectory());
Files.createDirectories(exportFileDirectory);
final Path exportFile = exportFileDirectory.resolve(getFileName());
try (RandomAccessFile randomAccessFile = new RandomAccessFile(exportFile.toFile(), "rw")) {
try (FileChannel fileChannel = randomAccessFile.getChannel()) {
// Add a header if the file is empty
if (randomAccessFile.length() == 0L) {
fileChannel.write(toByteBuffer(TAB_JOINER.join(getHeader())));
fileChannel.write(toByteBuffer(CR_LF));
}
// We want to append rows, if the file already exists, so jump to the end
fileChannel.position(fileChannel.size());
/*
* XXX: createSearchRequestBuilder() should handle namespace/language code
* filtering, if applicable; we will only handle the effective time and module
* filters here.
*
* An effective time filter is always set, even if not in delta mode, to prevent
* exporting unpublished content twice.
*/
new BranchRequest<R>(branch, new RevisionIndexReadRequest<>(inner -> {
createSearchRequestBuilder().filterByModules(// null value will be ignored
modules).filterByEffectiveTime(effectiveTimeStart, effectiveTimeEnd).setLimit(BATCH_SIZE).setFields(Arrays.asList(getHeader())).stream(inner).flatMap(hits -> getMappedStream(hits, context, branch)).forEachOrdered(row -> {
String id = row.get(0);
String effectiveTime = row.get(1);
if (!visitedComponentEffectiveTimes.add(String.join("_", id, effectiveTime))) {
return;
}
try {
fileChannel.write(toByteBuffer(TAB_JOINER.join(row)));
fileChannel.write(toByteBuffer(CR_LF));
} catch (final IOException e) {
throw new SnowowlRuntimeException("Failed to write contents for file '" + exportFile.getFileName() + "'.");
}
});
return null;
})).execute(context);
}
}
}
Aggregations