Search in sources :

Example 46 with ResourceURI

use of com.b2international.snowowl.core.ResourceURI in project snow-owl by b2ihealthcare.

the class CodeSystemUpgradeRequest method execute.

@Override
public String execute(RepositoryContext context) {
    // get available upgrades
    final CodeSystem currentCodeSystem = CodeSystemRequests.prepareGetCodeSystem(resource.getResourceId()).setExpand(CodeSystem.Expand.AVAILABLE_UPGRADES + "()").build().execute(context);
    if (currentCodeSystem.getUpgradeOf() != null) {
        throw new BadRequestException("Upgrade can not be started on an existing upgrade resource");
    }
    final List<ResourceURI> availableUpgrades = currentCodeSystem.getAvailableUpgrades();
    // report bad request if there are no upgrades available
    if (availableUpgrades.isEmpty()) {
        throw new BadRequestException("There are no upgrades available for resource '%s'.", resource.getResourceId());
    }
    // or the selected extensionOf version is not present as a valid available upgrade
    if (!availableUpgrades.contains(extensionOf)) {
        throw new BadRequestException("Upgrades can only be performed to the next available version dependency.").withDeveloperMessage("Use '%s/<VERSION_ID>', where <VERSION_ID> is one of: '%s'", extensionOf.getResourceId(), availableUpgrades);
    }
    // auto-generate the resourceId if not provided
    // auto-generated upgrade IDs consist of the original Resource's ID and the new extensionOf dependency's path, which is version at this point
    final String upgradeResourceId;
    if (resourceId == null) {
        upgradeResourceId = String.format("%s-%s-UPGRADE", resource.getResourceId(), extensionOf.getPath());
    } else if (resourceId.isBlank()) {
        throw new BadRequestException("'resourceId' property should not be empty, if provided");
    } else {
        BranchNameValidator.DEFAULT.checkName(resourceId);
        upgradeResourceId = resourceId;
    }
    String mergeContentFromBranchPath = currentCodeSystem.getBranchPath();
    // only allow HEAD or valid code system versions
    if (!resource.isHead()) {
        mergeContentFromBranchPath = new DefaultResourceURIPathResolver(false).resolve(context, List.of(resource)).stream().findFirst().get();
    }
    // create the same branch name under the new extensionOf path
    String parentBranch = context.service(ResourceURIPathResolver.class).resolve(context, List.of(extensionOf)).stream().findFirst().get();
    // merge content in the tooling repository from the current resource's to the upgrade resource's branch
    final String upgradeBranch = RepositoryRequests.branching().prepareCreate().setParent(parentBranch).setName(resource.getResourceId()).build(currentCodeSystem.getToolingId()).getRequest().execute(context);
    try {
        // merge branch content from the current code system to the new upgradeBranch
        Merge merge = RepositoryRequests.merging().prepareCreate().setSource(mergeContentFromBranchPath).setTarget(upgradeBranch).setSquash(false).build(currentCodeSystem.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 can not be performed due to content synchronization errors.").withAdditionalInfo(Map.of("conflicts", conflicts, "mergeError", apiError.getMessage()));
        }
        // and lastly create the actual CodeSystem so users will be able to browse, access and complete the upgrade
        return CodeSystemRequests.prepareNewCodeSystem().setId(upgradeResourceId).setBranchPath(upgradeBranch).setTitle(String.format("Upgrade of '%s' to '%s'", currentCodeSystem.getTitle(), extensionOf)).setUrl(currentCodeSystem.getUrl() + "?upgrade=" + upgradeResourceId).setLanguage(currentCodeSystem.getLanguage()).setDescription(currentCodeSystem.getDescription()).setStatus("draft").setCopyright(currentCodeSystem.getCopyright()).setOwner(currentCodeSystem.getOwner()).setContact(currentCodeSystem.getContact()).setUsage(currentCodeSystem.getUsage()).setPurpose(currentCodeSystem.getPurpose()).setToolingId(currentCodeSystem.getToolingId()).setExtensionOf(extensionOf).setUpgradeOf(resource).setSettings(currentCodeSystem.getSettings()).commit().setCommitComment(String.format("Start upgrade of '%s' to '%s'", resource, extensionOf)).build().execute(context.openBranch(context, Branch.MAIN_PATH)).getResultAs(String.class);
    } catch (Throwable e) {
        // delete upgrade branch if any exception have been thrown during the upgrade
        RepositoryRequests.branching().prepareDelete(upgradeBranch).build(currentCodeSystem.getToolingId()).getRequest().execute(context);
        throw e;
    }
}
Also used : MergeConflict(com.b2international.snowowl.core.merge.MergeConflict) ResourceURI(com.b2international.snowowl.core.ResourceURI) DefaultResourceURIPathResolver(com.b2international.snowowl.core.uri.DefaultResourceURIPathResolver) Merge(com.b2international.snowowl.core.merge.Merge) ConflictException(com.b2international.commons.exceptions.ConflictException) BadRequestException(com.b2international.commons.exceptions.BadRequestException) ApiError(com.b2international.commons.exceptions.ApiError)

Example 47 with ResourceURI

use of com.b2international.snowowl.core.ResourceURI in project snow-owl by b2ihealthcare.

the class TerminologyResourceRequest method initialize.

private void initialize(ServiceProvider context) {
    if (resourcePath.startsWith(Branch.MAIN_PATH)) {
        context.log().warn("Reflective access of terminology resources ('{}/{}') is not the recommended way of accessing resources. Consider using Resource IDs and relative branch path expressions.", toolingId, resourcePath);
        this.resource = context.service(PathTerminologyResourceResolver.class).resolve(context, toolingId, resourcePath);
        this.resourceUri = resource.getResourceURI(resourcePath);
        this.branchPath = resourcePath;
    } else {
        // resourcePaths are just ID/PATH style expressions to reference content in a terminology repository
        final ResourceURI referenceResourceUri = ResourceURI.of("any", resourcePath);
        Resource resource = ResourceRequests.prepareGet(referenceResourceUri).buildAsync().getRequest().execute(context);
        if (!(resource instanceof TerminologyResource)) {
            throw new NotFoundException("Terminology Resource", referenceResourceUri.getResourceId());
        }
        this.resource = (TerminologyResource) resource;
        this.resourceUri = this.resource.getResourceURI().withPath(referenceResourceUri.getPath()).withTimestampPart(referenceResourceUri.getTimestampPart());
        this.branchPath = context.service(ResourceURIPathResolver.class).resolve(context, referenceResourceUri, resource);
    }
}
Also used : ResourceURI(com.b2international.snowowl.core.ResourceURI) TerminologyResource(com.b2international.snowowl.core.TerminologyResource) Resource(com.b2international.snowowl.core.Resource) TerminologyResource(com.b2international.snowowl.core.TerminologyResource) NotFoundException(com.b2international.commons.exceptions.NotFoundException)

Example 48 with ResourceURI

use of com.b2international.snowowl.core.ResourceURI in project snow-owl by b2ihealthcare.

the class ValueSetMemberSearchRequest method doExecute.

@Override
protected ValueSetMembers doExecute(ServiceProvider context) throws IOException {
    final int limit = limit();
    Options options = Options.builder().putAll(options()).put(MemberSearchRequestEvaluator.OptionKey.AFTER, searchAfter()).put(MemberSearchRequestEvaluator.OptionKey.LIMIT, limit).put(MemberSearchRequestEvaluator.OptionKey.LOCALES, locales()).put(SearchResourceRequest.OptionKey.SORT_BY, sortBy()).build();
    // extract all ValueSetMemberSearchRequestEvaluator from all connected toolings and determine which ones can handle this request
    List<ValueSetMembers> evaluatedMembers = context.service(RepositoryManager.class).repositories().stream().flatMap(repository -> {
        ValueSetMemberSearchRequestEvaluator evaluator = repository.service(ValueSetMemberSearchRequestEvaluator.class);
        Set<ResourceURI> targets = evaluator.evaluateSearchTargetResources(context, options);
        return targets.stream().map(uri -> {
            return evaluator.evaluate(uri, context, options);
        });
    }).collect(Collectors.toList());
    // calculate grand total
    int total = 0;
    for (ValueSetMembers evaluatedMember : evaluatedMembers) {
        total += evaluatedMember.getTotal();
    }
    return new ValueSetMembers(// TODO add manual sorting here if multiple resources have been fetched
    evaluatedMembers.stream().flatMap(ValueSetMembers::stream).limit(limit).collect(Collectors.toList()), null, /* not supported across resources, TODO support it when a single ValueSet is being fetched */
    limit, total);
}
Also used : List(java.util.List) Options(com.b2international.commons.options.Options) RepositoryManager(com.b2international.snowowl.core.RepositoryManager) ServiceProvider(com.b2international.snowowl.core.ServiceProvider) Set(java.util.Set) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) ValueSetMembers(com.b2international.snowowl.core.domain.ValueSetMembers) ResourceURI(com.b2international.snowowl.core.ResourceURI) Options(com.b2international.commons.options.Options) Set(java.util.Set) ValueSetMembers(com.b2international.snowowl.core.domain.ValueSetMembers)

Example 49 with ResourceURI

use of com.b2international.snowowl.core.ResourceURI in project snow-owl by b2ihealthcare.

the class SnomedConceptApiTest method testConceptInactivationModuleChanges.

@Test
public void testConceptInactivationModuleChanges() {
    final String conceptId = createNewConcept(branchPath);
    final String moduleConceptId = createNewConcept(branchPath);
    String sourceRelationshipId = createNewRelationship(branchPath, conceptId, Concepts.HAS_DOSE_FORM, Concepts.MODULE_SCT_MODEL_COMPONENT);
    String destinationRelationshipId = createNewRelationship(branchPath, Concepts.MODULE_SCT_MODEL_COMPONENT, Concepts.HAS_DOSE_FORM, conceptId);
    ResourceURI codeSystemURI = SnomedContentRule.SNOMEDCT.withPath(branchPath.getPath().replace(Branch.MAIN_PATH + "/", ""));
    SnomedRelationship sourceRelationship = SnomedRequests.prepareGetRelationship(sourceRelationshipId).build(codeSystemURI).execute(getBus()).getSync();
    SnomedRelationship destinationRelationship = SnomedRequests.prepareGetRelationship(destinationRelationshipId).build(codeSystemURI).execute(getBus()).getSync();
    Request<TransactionContext, Boolean> request = SnomedRequests.prepareUpdateConcept(conceptId).setActive(false).build();
    SnomedRequests.prepareCommit().setDefaultModuleId(moduleConceptId).setBody(request).setCommitComment("commit").build(codeSystemURI).execute(getBus()).getSync();
    SnomedRelationship updatedSourceRelationship = SnomedRequests.prepareGetRelationship(sourceRelationshipId).build(codeSystemURI).execute(getBus()).getSync();
    SnomedRelationship updatedDestinationRelationship = SnomedRequests.prepareGetRelationship(destinationRelationshipId).build(codeSystemURI).execute(getBus()).getSync();
    // Before update
    assertTrue(sourceRelationship.isActive());
    assertTrue(destinationRelationship.isActive());
    assertFalse(moduleConceptId.equals(sourceRelationship.getModuleId()));
    assertFalse(moduleConceptId.equals(destinationRelationship.getModuleId()));
    // After update
    assertFalse(updatedSourceRelationship.isActive());
    assertEquals(moduleConceptId, updatedSourceRelationship.getModuleId());
    assertFalse(updatedDestinationRelationship.isActive());
    assertEquals(moduleConceptId, updatedDestinationRelationship.getModuleId());
}
Also used : ResourceURI(com.b2international.snowowl.core.ResourceURI) TransactionContext(com.b2international.snowowl.core.domain.TransactionContext) Test(org.junit.Test)

Aggregations

ResourceURI (com.b2international.snowowl.core.ResourceURI)49 Test (org.junit.Test)29 CodeSystem (com.b2international.snowowl.core.codesystem.CodeSystem)21 LocalDate (java.time.LocalDate)19 Collectors (java.util.stream.Collectors)11 TerminologyResource (com.b2international.snowowl.core.TerminologyResource)7 List (java.util.List)7 Set (java.util.Set)7 BadRequestException (com.b2international.commons.exceptions.BadRequestException)6 Options (com.b2international.commons.options.Options)6 CodeSystemRequests (com.b2international.snowowl.core.codesystem.CodeSystemRequests)6 IEventBus (com.b2international.snowowl.eventbus.IEventBus)6 IOException (java.io.IOException)6 Map (java.util.Map)6 TimeUnit (java.util.concurrent.TimeUnit)6 RepositoryManager (com.b2international.snowowl.core.RepositoryManager)5 ServiceProvider (com.b2international.snowowl.core.ServiceProvider)5 CodeSystems (com.b2international.snowowl.core.codesystem.CodeSystems)5 Version (com.b2international.snowowl.core.version.Version)5 Strings (com.google.common.base.Strings)5