Search in sources :

Example 6 with Branch

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

the class ClassificationSaveRequest method execute.

@Override
public String execute(final RepositoryContext context) {
    final Request<RepositoryContext, ClassificationTask> classificationRequest = ClassificationRequests.prepareGetClassification(classificationId).build();
    final ClassificationTask classification = classificationRequest.execute(context);
    final String branchPath = classification.getBranch();
    final Request<RepositoryContext, Branch> branchRequest = RepositoryRequests.branching().prepareGet(branchPath).build();
    final Branch branch = branchRequest.execute(context);
    if (!SAVEABLE_STATUSES.contains(classification.getStatus())) {
        throw new BadRequestException("Classification '%s' is not in the expected state to start saving changes.", classificationId);
    }
    if (classification.getTimestamp() < branch.headTimestamp()) {
        throw new BadRequestException("Classification '%s' on branch '%s' is stale (classification timestamp: %s, head timestamp: %s).", classificationId, branchPath, classification.getTimestamp(), branch.headTimestamp());
    }
    final String user = !Strings.isNullOrEmpty(userId) ? userId : context.service(User.class).getUsername();
    final AsyncRequest<?> saveRequest = new SaveJobRequestBuilder().setClassificationId(classificationId).setUserId(user).setParentLockContext(parentLockContext).setCommitComment(commitComment).setModuleId(moduleId).setNamespace(namespace).setAssignerType(assignerType).setFixEquivalences(fixEquivalences).setHandleConcreteDomains(handleConcreteDomains).build(branchPath);
    return JobRequests.prepareSchedule().setUser(userId).setRequest(saveRequest).setDescription(String.format("Saving classification changes on %s", branch.path())).buildAsync().get(context, SCHEDULE_TIMEOUT_MILLIS);
}
Also used : RepositoryContext(com.b2international.snowowl.core.domain.RepositoryContext) ClassificationTask(com.b2international.snowowl.snomed.reasoner.domain.ClassificationTask) Branch(com.b2international.snowowl.core.branch.Branch) BadRequestException(com.b2international.commons.exceptions.BadRequestException)

Example 7 with Branch

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

the class ClassificationCreateRequest method execute.

@Override
public String execute(final BranchContext context) {
    final String repositoryId = context.info().id();
    final Branch branch = context.branch();
    final ClassificationTracker tracker = context.service(ClassificationTracker.class);
    final SnomedCoreConfiguration config = context.service(SnomedCoreConfiguration.class);
    final String user = !Strings.isNullOrEmpty(userId) ? userId : context.service(User.class).getUsername();
    tracker.classificationScheduled(classificationId, reasonerId, user, branch.path());
    final AsyncRequest<Boolean> jobRequest = new ClassificationJobRequestBuilder().setReasonerId(reasonerId).setParentLockContext(parentLockContext).addAllConcepts(additionalConcepts).build(branch.path());
    final ClassificationSchedulingRule rule = ClassificationSchedulingRule.create(config.getMaxReasonerCount(), repositoryId, branch.path());
    JobRequests.prepareSchedule().setKey(classificationId).setUser(user).setRequest(jobRequest).setDescription(String.format("Classifying the ontology on %s", branch.path())).setSchedulingRule(rule).buildAsync().get(context, SCHEDULE_TIMEOUT_MILLIS);
    return classificationId;
}
Also used : Branch(com.b2international.snowowl.core.branch.Branch) SnomedCoreConfiguration(com.b2international.snowowl.snomed.datastore.config.SnomedCoreConfiguration) ClassificationSchedulingRule(com.b2international.snowowl.snomed.reasoner.classification.ClassificationSchedulingRule) ClassificationTracker(com.b2international.snowowl.snomed.reasoner.classification.ClassificationTracker)

Example 8 with Branch

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

the class ClassificationJobRequest method execute.

@Override
public Boolean execute(final BranchContext context) {
    final RemoteJob job = context.service(RemoteJob.class);
    final String classificationId = job.getKey();
    final Branch branch = context.branch();
    final long headTimestamp = branch.headTimestamp();
    final ClassificationTracker tracker = context.service(ClassificationTracker.class);
    tracker.classificationRunning(classificationId, headTimestamp);
    try {
        executeClassification(context, classificationId, tracker);
    } catch (final ReasonerApiException e) {
        tracker.classificationFailed(classificationId);
        throw e;
    } catch (final Exception e) {
        LOGGER.error("Unexpected error encountered while running classification job.", e);
        tracker.classificationFailed(classificationId);
        throw new ReasonerApiException("Exception caught while running classification.", e);
    }
    return Boolean.TRUE;
}
Also used : RemoteJob(com.b2international.snowowl.core.jobs.RemoteJob) Branch(com.b2international.snowowl.core.branch.Branch) ReasonerApiException(com.b2international.snowowl.snomed.reasoner.exceptions.ReasonerApiException) ClassificationTracker(com.b2international.snowowl.snomed.reasoner.classification.ClassificationTracker) OWLOntologyCreationException(org.semanticweb.owlapi.model.OWLOntologyCreationException) ReasonerInterruptedException(org.semanticweb.owlapi.reasoner.ReasonerInterruptedException) OWLReasonerRuntimeException(org.semanticweb.owlapi.reasoner.OWLReasonerRuntimeException) LockedException(com.b2international.commons.exceptions.LockedException) ReasonerApiException(com.b2international.snowowl.snomed.reasoner.exceptions.ReasonerApiException)

Example 9 with Branch

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

the class BranchCompareRequest method execute.

@Override
public BranchCompareResult execute(RepositoryContext context) {
    final RevisionIndex index = context.service(RevisionIndex.class);
    final Branch branchToCompare = RepositoryRequests.branching().prepareGet(compare).build().execute(context);
    final long compareHeadTimestamp = branchToCompare.headTimestamp();
    final RevisionCompare compareResult;
    final String baseBranchPath;
    if (base != null) {
        compareResult = index.compare(base, compare, limit, excludeComponentChanges);
        baseBranchPath = base;
    } else {
        compareResult = index.compare(compare, limit, excludeComponentChanges);
        baseBranchPath = branchToCompare.parentPath();
    }
    final BranchCompareResult.Builder result = BranchCompareResult.builder(baseBranchPath, compare, compareHeadTimestamp);
    final Set<ComponentIdentifier> changedContainers = Sets.newHashSet();
    for (RevisionCompareDetail detail : compareResult.getDetails()) {
        final ObjectId affectedId;
        if (detail.isComponentChange()) {
            affectedId = detail.getComponent();
            if (!detail.getObject().isRoot() && !excludeComponentChanges) {
                changedContainers.add(ComponentIdentifier.of(detail.getObject().type(), detail.getObject().id()));
            }
        } else {
            affectedId = detail.getObject();
        }
        final ComponentIdentifier identifier = ComponentIdentifier.of(affectedId.type(), affectedId.id());
        switch(detail.getOp()) {
            case ADD:
                result.putNewComponent(identifier);
                break;
            case CHANGE:
                result.putChangedComponent(identifier);
                break;
            case REMOVE:
                result.putDeletedComponent(identifier);
                break;
        }
    }
    return result.totalNew(compareResult.getTotalAdded()).totalChanged(compareResult.getTotalChanged()).totalDeleted(compareResult.getTotalRemoved()).build(changedContainers);
}
Also used : RevisionIndex(com.b2international.index.revision.RevisionIndex) ObjectId(com.b2international.index.revision.ObjectId) Branch(com.b2international.snowowl.core.branch.Branch) RevisionCompare(com.b2international.index.revision.RevisionCompare) ComponentIdentifier(com.b2international.snowowl.core.ComponentIdentifier) RevisionCompareDetail(com.b2international.index.revision.RevisionCompareDetail)

Example 10 with Branch

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

the class VersionCreateRequest method execute.

@Override
public Boolean execute(RepositoryContext context) {
    final String user = context.service(User.class).getUsername();
    if (!resource.isHead()) {
        throw new BadRequestException("Version '%s' cannot be created on unassigned branch '%s'.", version, resource).withDeveloperMessage("Did you mean to version '%s'?", resource.withoutPath());
    }
    if (resourcesById == null) {
        resourcesById = fetchResources(context);
    }
    if (!resourcesById.containsKey(resource)) {
        context.log().warn("Resource cannot be found during versioning: " + resourcesById + ", uri: " + resource);
        throw new NotFoundException("Resource", resource.getResourceId());
    }
    // validate new path
    RevisionBranch.BranchNameValidator.DEFAULT.checkName(version);
    TerminologyResource resourceToVersion = resourcesById.get(resource);
    // TODO resurrect or eliminate tooling dependencies
    final List<TerminologyResource> resourcesToVersion = List.of(resourcesById.get(resource));
    // final List<CodeSystem> resourcesToVersion = codeSystem.getDependenciesAndSelf()
    // .stream()
    // .map(resourcesById::get)
    // .collect(Collectors.toList());
    resourcesToVersion.stream().filter(cs -> cs.getUpgradeOf() != null).findAny().ifPresent(cs -> {
        throw new BadRequestException("Upgrade resource '%s' can not be versioned.", cs.getResourceURI());
    });
    for (TerminologyResource terminologyResource : resourcesToVersion) {
        // check that the new versionId does not conflict with any other currently available branch
        final String newVersionPath = String.join(Branch.SEPARATOR, terminologyResource.getBranchPath(), version);
        final String repositoryId = terminologyResource.getToolingId();
        if (!force) {
            // branch needs checking in the non-force cases only
            try {
                Branch branch = RepositoryRequests.branching().prepareGet(newVersionPath).build(repositoryId).execute(context);
                if (!branch.isDeleted()) {
                    throw new ConflictException("An existing version or branch with path '%s' conflicts with the specified version identifier.", newVersionPath);
                }
            } catch (NotFoundException e) {
            // branch does not exist, ignore
            }
        } else {
            // if there is no conflict, delete the branch (the request also ignores non-existent branches)
            deleteBranch(context, newVersionPath, repositoryId);
        }
    }
    acquireLocks(context, user, resourcesToVersion);
    final IProgressMonitor monitor = SubMonitor.convert(context.service(IProgressMonitor.class), TASK_WORK_STEP);
    try {
        // resourcesToVersion.forEach(resourceToVersion -> {
        // check that the specified effective time is valid in this code system
        validateVersion(context, resourceToVersion);
        // version components in the given repository
        new RepositoryRequest<>(resourceToVersion.getToolingId(), new BranchRequest<>(resourceToVersion.getBranchPath(), new RevisionIndexReadRequest<CommitResult>(context.service(RepositoryManager.class).get(resourceToVersion.getToolingId()).service(VersioningRequestBuilder.class).build(new VersioningConfiguration(user, resourceToVersion.getResourceURI(), version, description, effectiveTime, force))))).execute(context);
        // tag the repository
        doTag(context, resourceToVersion, monitor);
        // create a version for the resource
        return new BranchRequest<>(Branch.MAIN_PATH, new ResourceRepositoryCommitRequestBuilder().setBody(tx -> {
            tx.add(VersionDocument.builder().id(resource.withPath(version).withoutResourceType()).version(version).description(description).effectiveTime(EffectiveTimes.getEffectiveTime(effectiveTime)).resource(resource).branchPath(resourceToVersion.getRelativeBranchPath(version)).author(user).createdAt(Instant.now().toEpochMilli()).updatedAt(Instant.now().toEpochMilli()).toolingId(resourceToVersion.getToolingId()).url(buildVersionUrl(context, resourceToVersion)).build());
            return Boolean.TRUE;
        }).setCommitComment(CompareUtils.isEmpty(commitComment) ? String.format("Version '%s' as of '%s'", resource, version) : commitComment).build()).execute(context).getResultAs(Boolean.class);
    } finally {
        releaseLocks(context);
        if (null != monitor) {
            monitor.done();
        }
    }
}
Also used : EffectiveTimes(com.b2international.snowowl.core.date.EffectiveTimes) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) java.util(java.util) SubMonitor(org.eclipse.core.runtime.SubMonitor) RevisionBranch(com.b2international.index.revision.RevisionBranch) Multimap(com.google.common.collect.Multimap) Branch(com.b2international.snowowl.core.branch.Branch) RepositoryRequests(com.b2international.snowowl.core.repository.RepositoryRequests) CREATE_VERSION(com.b2international.snowowl.core.internal.locks.DatastoreLockContextDescriptions.CREATE_VERSION) HashMultimap(com.google.common.collect.HashMultimap) AccessControl(com.b2international.snowowl.core.authorization.AccessControl) DatastoreLockTarget(com.b2international.snowowl.core.internal.locks.DatastoreLockTarget) Permission(com.b2international.snowowl.core.identity.Permission) DatastoreLockContext(com.b2international.snowowl.core.internal.locks.DatastoreLockContext) CompareUtils(com.b2international.commons.CompareUtils) com.b2international.snowowl.core(com.b2international.snowowl.core) NotFoundException(com.b2international.commons.exceptions.NotFoundException) com.b2international.snowowl.core.request(com.b2international.snowowl.core.request) Version(com.b2international.snowowl.core.version.Version) BadRequestException(com.b2international.commons.exceptions.BadRequestException) ConflictException(com.b2international.commons.exceptions.ConflictException) RepositoryContext(com.b2international.snowowl.core.domain.RepositoryContext) Request(com.b2international.snowowl.core.events.Request) JsonFormat(com.fasterxml.jackson.annotation.JsonFormat) Instant(java.time.Instant) NotNull(javax.validation.constraints.NotNull) Collectors(java.util.stream.Collectors) TerminologyRegistry(com.b2international.snowowl.core.terminology.TerminologyRegistry) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) VersionDocument(com.b2international.snowowl.core.version.VersionDocument) NotEmpty(org.hibernate.validator.constraints.NotEmpty) LocalDate(java.time.LocalDate) Sort(com.b2international.snowowl.core.request.SearchResourceRequest.Sort) Entry(java.util.Map.Entry) IOperationLockManager(com.b2international.snowowl.core.locks.IOperationLockManager) ResourceURLSchemaSupport(com.b2international.snowowl.core.uri.ResourceURLSchemaSupport) ResourceRepositoryCommitRequestBuilder(com.b2international.snowowl.core.context.ResourceRepositoryCommitRequestBuilder) User(com.b2international.snowowl.core.identity.User) User(com.b2international.snowowl.core.identity.User) ConflictException(com.b2international.commons.exceptions.ConflictException) NotFoundException(com.b2international.commons.exceptions.NotFoundException) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) RevisionBranch(com.b2international.index.revision.RevisionBranch) Branch(com.b2international.snowowl.core.branch.Branch) BadRequestException(com.b2international.commons.exceptions.BadRequestException) ResourceRepositoryCommitRequestBuilder(com.b2international.snowowl.core.context.ResourceRepositoryCommitRequestBuilder)

Aggregations

Branch (com.b2international.snowowl.core.branch.Branch)15 BadRequestException (com.b2international.commons.exceptions.BadRequestException)8 Request (com.b2international.snowowl.core.events.Request)7 RepositoryRequests (com.b2international.snowowl.core.repository.RepositoryRequests)6 RepositoryContext (com.b2international.snowowl.core.domain.RepositoryContext)5 RevisionBranch (com.b2international.index.revision.RevisionBranch)4 ResourceURI (com.b2international.snowowl.core.ResourceURI)4 ServiceProvider (com.b2international.snowowl.core.ServiceProvider)4 Merge (com.b2international.snowowl.core.merge.Merge)4 JsonProperty (com.fasterxml.jackson.annotation.JsonProperty)4 NotNull (javax.validation.constraints.NotNull)4 CompareUtils (com.b2international.commons.CompareUtils)3 NotFoundException (com.b2international.commons.exceptions.NotFoundException)3 BaseRevisionBranching (com.b2international.index.revision.BaseRevisionBranching)3 BranchPathUtils (com.b2international.snowowl.core.branch.BranchPathUtils)3 Branching (com.b2international.snowowl.core.branch.Branching)3 Merging (com.b2international.snowowl.core.branch.Merging)3 User (com.b2international.snowowl.core.identity.User)3 RemoteJobEntry (com.b2international.snowowl.core.jobs.RemoteJobEntry)3 CommitResult (com.b2international.snowowl.core.request.CommitResult)3