Search in sources :

Example 1 with Request

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

the class SnomedRf2ExportRequest method getIdentifierConcepts.

private List<SnomedConcept> getIdentifierConcepts(final RepositoryContext context, final String currentVersion) {
    final Collection<String> refSetsToLoad;
    if (refSets == null) {
        // Retrieve all reference sets if refSets is null
        final Request<BranchContext, SnomedReferenceSets> refSetRequest = SnomedRequests.prepareSearchRefSet().all().build();
        final SnomedReferenceSets allReferenceSets = execute(context, currentVersion, refSetRequest);
        refSetsToLoad = allReferenceSets.stream().map(r -> r.getId()).collect(Collectors.toSet());
    } else {
        refSetsToLoad = refSets;
    }
    final SnomedConceptSearchRequestBuilder refSetRequestBuilder = SnomedRequests.prepareSearchConcept().all().filterByIds(refSetsToLoad).setExpand("pt(),referenceSet()").setLocales(locales());
    final Request<BranchContext, SnomedConcepts> request = refSetRequestBuilder.build();
    final SnomedConcepts referenceSets = execute(context, currentVersion, request);
    // Return only the identifier concepts which have an existing reference set on this branch
    return referenceSets.stream().filter(c -> c.getReferenceSet() != null).collect(Collectors.toList());
}
Also used : JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) SnomedConceptSearchRequestBuilder(com.b2international.snowowl.snomed.datastore.request.SnomedConceptSearchRequestBuilder) SnomedRelationshipIndexEntry(com.b2international.snowowl.snomed.datastore.index.entry.SnomedRelationshipIndexEntry) SnomedReferenceSets(com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSets) RepositoryRequests(com.b2international.snowowl.core.repository.RepositoryRequests) Sets.newTreeSet(com.google.common.collect.Sets.newTreeSet) Collections.singleton(java.util.Collections.singleton) AccessControl(com.b2international.snowowl.core.authorization.AccessControl) LocalTime(java.time.LocalTime) RevisionIndex(com.b2international.index.revision.RevisionIndex) Sets.newHashSet(com.google.common.collect.Sets.newHashSet) AttachmentRegistry(com.b2international.snowowl.core.attachments.AttachmentRegistry) Branches(com.b2international.snowowl.core.branch.Branches) Permission(com.b2international.snowowl.core.identity.Permission) CompareUtils(com.b2international.commons.CompareUtils) Path(java.nio.file.Path) com.google.common.collect(com.google.common.collect) Collectors.toSet(java.util.stream.Collectors.toSet) ResourceURI(com.b2international.snowowl.core.ResourceURI) com.b2international.snowowl.core.request(com.b2international.snowowl.core.request) Version(com.b2international.snowowl.core.version.Version) RepositoryContext(com.b2international.snowowl.core.domain.RepositoryContext) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) Request(com.b2international.snowowl.core.events.Request) IEventBus(com.b2international.snowowl.eventbus.IEventBus) Instant(java.time.Instant) NotNull(javax.validation.constraints.NotNull) Collectors(java.util.stream.Collectors) Lists.newArrayList(com.google.common.collect.Lists.newArrayList) Stream(java.util.stream.Stream) VersionDocument(com.b2international.snowowl.core.version.VersionDocument) LocalDate(java.time.LocalDate) Sort(com.b2international.snowowl.core.request.SearchResourceRequest.Sort) Entry(java.util.Map.Entry) CodeSystemRequests(com.b2international.snowowl.core.codesystem.CodeSystemRequests) SnomedDescriptionIndexEntry(com.b2international.snowowl.snomed.datastore.index.entry.SnomedDescriptionIndexEntry) BranchContext(com.b2international.snowowl.core.domain.BranchContext) Builder(com.google.common.collect.ImmutableList.Builder) FileUtils(com.b2international.commons.FileUtils) CodeSystem(com.b2international.snowowl.core.codesystem.CodeSystem) EffectiveTimes(com.b2international.snowowl.core.date.EffectiveTimes) java.util(java.util) TerminologyResource(com.b2international.snowowl.core.TerminologyResource) LocalDateTime(java.time.LocalDateTime) com.b2international.snowowl.snomed.datastore.request.rf2.exporter(com.b2international.snowowl.snomed.datastore.request.rf2.exporter) com.b2international.snowowl.snomed.core.domain(com.b2international.snowowl.snomed.core.domain) Branch(com.b2international.snowowl.core.branch.Branch) Concepts(com.b2international.snowowl.snomed.common.SnomedConstants.Concepts) Strings(com.google.common.base.Strings) SnomedRequests(com.b2international.snowowl.snomed.datastore.request.SnomedRequests) Attachment(com.b2international.snowowl.core.attachments.Attachment) SnomedRefSetMemberSearchRequestBuilder(com.b2international.snowowl.snomed.datastore.request.SnomedRefSetMemberSearchRequestBuilder) BadRequestException(com.b2international.commons.exceptions.BadRequestException) BranchPathUtils(com.b2international.snowowl.core.branch.BranchPathUtils) DateFormats(com.b2international.snowowl.core.date.DateFormats) Files(java.nio.file.Files) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) SnomedTerminologyComponentConstants(com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) ChronoUnit(java.time.temporal.ChronoUnit) SnomedReferenceSetMember(com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMember) NotEmpty(org.hibernate.validator.constraints.NotEmpty) DateTimeFormatter(java.time.format.DateTimeFormatter) IComponent(com.b2international.snowowl.core.domain.IComponent) SnomedRf2Headers(com.b2international.snowowl.snomed.common.SnomedRf2Headers) Versions(com.b2international.snowowl.core.version.Versions) SnomedRefSetType(com.b2international.snowowl.snomed.core.domain.refset.SnomedRefSetType) BranchContext(com.b2international.snowowl.core.domain.BranchContext) SnomedReferenceSets(com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSets) SnomedConceptSearchRequestBuilder(com.b2international.snowowl.snomed.datastore.request.SnomedConceptSearchRequestBuilder)

Example 2 with Request

use of com.b2international.snowowl.core.events.Request 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()));
            }
        }
    }
}
Also used : SnomedConcept(com.b2international.snowowl.snomed.core.domain.SnomedConcept) BranchRequest(com.b2international.snowowl.core.request.BranchRequest) com.b2international.snowowl.snomed.reasoner.domain(com.b2international.snowowl.snomed.reasoner.domain) Multimap(com.google.common.collect.Multimap) Multimaps(com.google.common.collect.Multimaps) ExtendedLocale(com.b2international.commons.http.ExtendedLocale) SnomedRequests(com.b2international.snowowl.snomed.datastore.request.SnomedRequests) Options(com.b2international.commons.options.Options) FluentIterable(com.google.common.collect.FluentIterable) Map(java.util.Map) DescriptionChangeDocument(com.b2international.snowowl.snomed.reasoner.index.DescriptionChangeDocument) SnomedDescriptions(com.b2international.snowowl.snomed.core.domain.SnomedDescriptions) RepositoryContext(com.b2international.snowowl.core.domain.RepositoryContext) ClassificationRequests(com.b2international.snowowl.snomed.reasoner.request.ClassificationRequests) Collection(java.util.Collection) Request(com.b2international.snowowl.core.events.Request) SnomedConcepts(com.b2international.snowowl.snomed.core.domain.SnomedConcepts) Set(java.util.Set) Collectors(java.util.stream.Collectors) Maps(com.google.common.collect.Maps) RevisionIndexReadRequest(com.b2international.snowowl.core.request.RevisionIndexReadRequest) SnomedDescription(com.b2international.snowowl.snomed.core.domain.SnomedDescription) List(java.util.List) BranchContext(com.b2international.snowowl.core.domain.BranchContext) BaseResourceConverter(com.b2international.snowowl.core.request.BaseResourceConverter) Options(com.b2international.commons.options.Options) SnomedDescription(com.b2international.snowowl.snomed.core.domain.SnomedDescription) SnomedDescriptions(com.b2international.snowowl.snomed.core.domain.SnomedDescriptions) RevisionIndexReadRequest(com.b2international.snowowl.core.request.RevisionIndexReadRequest) SnomedConcepts(com.b2international.snowowl.snomed.core.domain.SnomedConcepts) SnomedConcept(com.b2international.snowowl.snomed.core.domain.SnomedConcept) BranchContext(com.b2international.snowowl.core.domain.BranchContext)

Example 3 with Request

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

the class CommitInfoRequestTest method getCommitInfoByComment.

private CommitInfo getCommitInfoByComment(final String comment) {
    Request<RepositoryContext, CommitInfos> req = RepositoryRequests.commitInfos().prepareSearchCommitInfo().filterByComment(comment).build();
    final CommitInfos commitInfos = new ResourceRepositoryRequestBuilder<CommitInfos>() {

        @Override
        public Request<RepositoryContext, CommitInfos> build() {
            return req;
        }
    }.buildAsync().execute(bus).getSync();
    assertEquals(commitInfos.getTotal(), 1);
    return Iterables.getOnlyElement(commitInfos);
}
Also used : CommitInfos(com.b2international.snowowl.core.commit.CommitInfos) RepositoryContext(com.b2international.snowowl.core.domain.RepositoryContext) Request(com.b2international.snowowl.core.events.Request) AuthorizedRequest(com.b2international.snowowl.core.authorization.AuthorizedRequest)

Example 4 with Request

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

the class AuthorizedRequest method execute.

@Override
public R execute(ServiceProvider context) {
    final RequestHeaders requestHeaders = context.service(RequestHeaders.class);
    final String authorizationToken = requestHeaders.header(AUTHORIZATION_HEADER);
    final IdentityProvider identityProvider = context.service(IdentityProvider.class);
    final Collection<Request<?, ?>> requests = getNestedRequests();
    final User user;
    // if there is no authentication configured
    if (IdentityProvider.NOOP == identityProvider) {
        // allow execution as SYSTEM user
        user = User.SYSTEM;
    } else if (Strings.isNullOrEmpty(authorizationToken)) {
        // allow login requests in
        if (requests.stream().allMatch(req -> req.getClass().isAnnotationPresent(Unprotected.class))) {
            user = User.SYSTEM;
        } else {
            // if there is authentication configured, but no authorization token found prevent execution and throw UnauthorizedException
            if (PlatformUtil.isDevVersion()) {
                Request<?, ?> request = Iterables.getFirst(requests, null);
                System.err.println(request);
            }
            throw new UnauthorizedException("Missing authorization token");
        }
    } else {
        // verify authorization header value
        user = context.service(AuthorizationHeaderVerifier.class).auth(authorizationToken);
        if (user == null) {
            throw new UnauthorizedException("Incorrect authorization token");
        }
    }
    ServiceProvider userContext = context.inject().bind(User.class, user).bind(IEventBus.class, new AuthorizedEventBus(context.service(IEventBus.class), requestHeaders.headers())).build();
    if (!User.SYSTEM.equals(user) && !user.isAdministrator()) {
        // authorize user whether it is permitted to execute the request(s) or not
        requests.stream().filter(AccessControl.class::isInstance).map(AccessControl.class::cast).flatMap(ac -> {
            List<Permission> permissions = ac.getPermissions(userContext, next());
            if (permissions.isEmpty()) {
                context.log().warn("No permissions required to execute request '{}'.", MonitoredRequest.toJson(context, next(), Map.of()));
            }
            return permissions.stream();
        }).forEach(permissionRequirement -> {
            if (!user.hasPermission(permissionRequirement)) {
                throw new ForbiddenException("Operation not permitted. '%s' permission is required. User has '%s'.", permissionRequirement.getPermission(), user.getPermissions());
            }
        });
    }
    return next(userContext);
}
Also used : ForbiddenException(com.b2international.commons.exceptions.ForbiddenException) IdentityProvider(com.b2international.snowowl.core.identity.IdentityProvider) RequestHeaders(com.b2international.snowowl.core.events.util.RequestHeaders) Iterables(com.google.common.collect.Iterables) UnauthorizedException(com.b2international.commons.exceptions.UnauthorizedException) Collection(java.util.Collection) Request(com.b2international.snowowl.core.events.Request) IEventBus(com.b2international.snowowl.eventbus.IEventBus) Strings(com.google.common.base.Strings) List(java.util.List) AuthorizationHeaderVerifier(com.b2international.snowowl.core.identity.AuthorizationHeaderVerifier) PlatformUtil(com.b2international.snowowl.core.util.PlatformUtil) Map(java.util.Map) ServiceProvider(com.b2international.snowowl.core.ServiceProvider) DelegatingRequest(com.b2international.snowowl.core.events.DelegatingRequest) Permission(com.b2international.snowowl.core.identity.Permission) User(com.b2international.snowowl.core.identity.User) MonitoredRequest(com.b2international.snowowl.core.monitoring.MonitoredRequest) ForbiddenException(com.b2international.commons.exceptions.ForbiddenException) User(com.b2international.snowowl.core.identity.User) AuthorizationHeaderVerifier(com.b2international.snowowl.core.identity.AuthorizationHeaderVerifier) Request(com.b2international.snowowl.core.events.Request) DelegatingRequest(com.b2international.snowowl.core.events.DelegatingRequest) MonitoredRequest(com.b2international.snowowl.core.monitoring.MonitoredRequest) IdentityProvider(com.b2international.snowowl.core.identity.IdentityProvider) ServiceProvider(com.b2international.snowowl.core.ServiceProvider) UnauthorizedException(com.b2international.commons.exceptions.UnauthorizedException) List(java.util.List) RequestHeaders(com.b2international.snowowl.core.events.util.RequestHeaders) IEventBus(com.b2international.snowowl.eventbus.IEventBus)

Example 5 with Request

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

the class CommitInfoRequestTest method getCommitInfo.

@Test
public void getCommitInfo() {
    final String oid = UUID.randomUUID().toString();
    final String shortName = UUID.randomUUID().toString();
    final String comment = "Code system for commit info 1";
    createCodeSystem(oid, shortName, comment);
    final String id = getCommitInfoByComment(comment).getId();
    Request<RepositoryContext, CommitInfo> req = RepositoryRequests.commitInfos().prepareGetCommitInfo(id).build();
    CommitInfo commitInfo = new ResourceRepositoryRequestBuilder<CommitInfo>() {

        @Override
        public Request<RepositoryContext, CommitInfo> build() {
            return req;
        }
    }.buildAsync().execute(bus).getSync();
    assertEquals(id, commitInfo.getId());
    assertEquals(comment, commitInfo.getComment());
    assertEquals(BRANCH, commitInfo.getBranch());
    assertEquals(USER_ID, commitInfo.getAuthor());
}
Also used : RepositoryContext(com.b2international.snowowl.core.domain.RepositoryContext) Request(com.b2international.snowowl.core.events.Request) AuthorizedRequest(com.b2international.snowowl.core.authorization.AuthorizedRequest) CommitInfo(com.b2international.snowowl.core.commit.CommitInfo) Test(org.junit.Test)

Aggregations

Request (com.b2international.snowowl.core.events.Request)14 RepositoryContext (com.b2international.snowowl.core.domain.RepositoryContext)10 BranchContext (com.b2international.snowowl.core.domain.BranchContext)7 Collectors (java.util.stream.Collectors)7 BadRequestException (com.b2international.commons.exceptions.BadRequestException)6 Collection (java.util.Collection)6 SnomedRequests (com.b2international.snowowl.snomed.datastore.request.SnomedRequests)5 Multimap (com.google.common.collect.Multimap)5 Map (java.util.Map)5 Set (java.util.Set)5 ExtendedLocale (com.b2international.commons.http.ExtendedLocale)4 Options (com.b2international.commons.options.Options)4 AuthorizedRequest (com.b2international.snowowl.core.authorization.AuthorizedRequest)4 BaseResourceConverter (com.b2international.snowowl.core.request.BaseResourceConverter)4 BranchRequest (com.b2international.snowowl.core.request.BranchRequest)4 RevisionIndexReadRequest (com.b2international.snowowl.core.request.RevisionIndexReadRequest)4 List (java.util.List)4 CompareUtils (com.b2international.commons.CompareUtils)3 Branch (com.b2international.snowowl.core.branch.Branch)3 CommitInfo (com.b2international.snowowl.core.commit.CommitInfo)3