Search in sources :

Example 6 with ServiceProvider

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

the class SnowOwlCommandProvider method _snowowl.

public void _snowowl(CommandInterpreter interpreter) throws Exception {
    // first read all args into an array
    List<String> args = newArrayList();
    String arg;
    while ((arg = interpreter.nextArgument()) != null) {
        args.add(arg);
    }
    final Environment env = ApplicationContext.getServiceForClass(Environment.class);
    final List<CommandLine> commands = cli(env).parse(args.toArray(new String[] {}));
    try (InterpreterStream out = new InterpreterStream(interpreter)) {
        // print help if requested for any command
        if (CommandLine.printHelpIfRequested(commands, out, out, CommandLine.Help.Ansi.AUTO)) {
            return;
        }
        // get the last command used in the cli
        CommandLine cli = Iterables.getLast(commands, null);
        if (cli == null) {
            return;
        }
        // we should get an executable Snow Owl Command, so execute it
        BaseCommand cmd = (BaseCommand) cli.getCommand();
        final String authorizationToken = ApplicationContext.getServiceForClass(JWTGenerator.class).generate(User.SYSTEM);
        final ServiceProvider context = env.inject().bind(IEventBus.class, new AuthorizedEventBus(ApplicationContext.getServiceForClass(IEventBus.class), ImmutableMap.of(AuthorizedRequest.AUTHORIZATION_HEADER, authorizationToken))).build();
        cmd.setContext(context);
        cmd.run(out);
    } catch (Exception e) {
        interpreter.println("Unknown error occured");
        interpreter.printStackTrace(e);
    }
}
Also used : CommandLine(picocli.CommandLine) JWTGenerator(com.b2international.snowowl.core.identity.JWTGenerator) ServiceProvider(com.b2international.snowowl.core.ServiceProvider) Environment(com.b2international.snowowl.core.setup.Environment) AuthorizedEventBus(com.b2international.snowowl.core.authorization.AuthorizedEventBus) IEventBus(com.b2international.snowowl.eventbus.IEventBus) IOException(java.io.IOException)

Example 7 with ServiceProvider

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

the class ConceptMapCompareDsvExportRequest method execute.

@Override
public File execute(ServiceProvider context) {
    final List<ConceptMapCompareResultItem> resultsToExport = items.stream().filter(item -> changeKinds.contains(item.getChangeKind())).collect(Collectors.toList());
    final CsvMapper mapper = new CsvMapper();
    final CsvSchema schema = mapper.schemaFor(ConceptMapCompareResultItem.class).withHeader().withoutQuoteChar().withColumnSeparator(delimiter).withNullValue("");
    try (OutputStream newOutputStream = Files.newOutputStream(Paths.get(filePath), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
        mapper.writer(schema).writeValue(newOutputStream, resultsToExport);
    } catch (Exception e) {
        throw new BadRequestException("An error occured durin Concept Map Compare DSV export: %s", Throwables.getRootCause(e).getMessage());
    }
    return Paths.get(filePath).toFile();
}
Also used : OutputStream(java.io.OutputStream) BadRequestException(com.b2international.commons.exceptions.BadRequestException) Files(java.nio.file.Files) Request(com.b2international.snowowl.core.events.Request) CsvMapper(com.fasterxml.jackson.dataformat.csv.CsvMapper) StandardOpenOption(java.nio.file.StandardOpenOption) CsvSchema(com.fasterxml.jackson.dataformat.csv.CsvSchema) Set(java.util.Set) Throwables(com.google.common.base.Throwables) Collectors(java.util.stream.Collectors) File(java.io.File) List(java.util.List) Paths(java.nio.file.Paths) ConceptMapCompareChangeKind(com.b2international.snowowl.core.compare.ConceptMapCompareChangeKind) ServiceProvider(com.b2international.snowowl.core.ServiceProvider) ConceptMapCompareResultItem(com.b2international.snowowl.core.compare.ConceptMapCompareResultItem) CsvSchema(com.fasterxml.jackson.dataformat.csv.CsvSchema) CsvMapper(com.fasterxml.jackson.dataformat.csv.CsvMapper) OutputStream(java.io.OutputStream) BadRequestException(com.b2international.commons.exceptions.BadRequestException) ConceptMapCompareResultItem(com.b2international.snowowl.core.compare.ConceptMapCompareResultItem) BadRequestException(com.b2international.commons.exceptions.BadRequestException)

Example 8 with ServiceProvider

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

the class ComponentInactivationChangeProcessor method processInactivations.

private void processInactivations(StagingArea staging, RevisionSearcher searcher, Set<String> inactivatedConceptIds, Set<String> inactivatedComponentIds) throws IOException {
    // inactivate descriptions of inactivated concepts, take current description changes into account
    ServiceProvider context = (ServiceProvider) staging.getContext();
    ModuleIdProvider moduleIdProvider = context.service(ModuleIdProvider.class);
    if (!inactivatedConceptIds.isEmpty()) {
        final Multimap<String, RevisionDiff> changedMembersByReferencedComponentId = HashMultimap.create();
        staging.getChangedRevisions(SnomedRefSetMemberIndexEntry.class).forEach(diff -> {
            changedMembersByReferencedComponentId.put(((SnomedRefSetMemberIndexEntry) diff.newRevision).getReferencedComponentId(), diff);
        });
        // Inactivate active descriptions on inactive concepts
        try {
            Query.select(SnomedDescriptionIndexEntry.class).from(SnomedDescriptionIndexEntry.class).fields(SnomedDescriptionIndexEntry.Fields.ID, SnomedDescriptionIndexEntry.Fields.MODULE_ID).where(Expressions.builder().filter(SnomedDescriptionIndexEntry.Expressions.active()).filter(SnomedDescriptionIndexEntry.Expressions.concepts(inactivatedConceptIds)).build()).limit(PAGE_SIZE).build().stream(searcher).forEachOrdered(hits -> {
                try {
                    inactivateDescriptions(searcher, moduleIdProvider, changedMembersByReferencedComponentId, hits);
                } catch (IOException e) {
                    throw new UndeclaredThrowableException(e);
                }
            });
        } catch (UndeclaredThrowableException ute) {
            // Unwrap and throw checked exception from lambda above
            throw (IOException) ute.getCause();
        }
        final Map<ObjectId, RevisionDiff> changedRevisions = staging.getChangedRevisions();
        // Inactivate active relationships on inactive concepts
        Query.select(SnomedRelationshipIndexEntry.class).where(Expressions.builder().filter(SnomedRelationshipIndexEntry.Expressions.active()).should(SnomedRelationshipIndexEntry.Expressions.sourceIds(inactivatedConceptIds)).should(SnomedRelationshipIndexEntry.Expressions.destinationIds(inactivatedConceptIds)).build()).limit(PAGE_SIZE).build().stream(searcher).flatMap(Hits::stream).forEachOrdered(relationship -> inactivateRelationship(inactivatedComponentIds, moduleIdProvider, changedRevisions, relationship));
    }
    if (inactivatedComponentIds.isEmpty()) {
        return;
    }
    // inactivate referring members of all inactivated core component, and all members of inactivated refsets
    final Map<ObjectId, RevisionDiff> changedRevisions = staging.getChangedRevisions();
    Query.select(SnomedRefSetMemberIndexEntry.class).where(Expressions.builder().filter(SnomedRefSetMemberIndexEntry.Expressions.active()).should(SnomedRefSetMemberIndexEntry.Expressions.referencedComponentIds(inactivatedComponentIds)).should(SnomedRefSetMemberIndexEntry.Expressions.refsetIds(inactivatedComponentIds)).setMinimumNumberShouldMatch(1).build()).limit(PAGE_SIZE).build().stream(searcher).flatMap(Hits::stream).forEachOrdered(member -> inactivateReferenceSetMember(moduleIdProvider, changedRevisions, member));
}
Also used : ObjectId(com.b2international.index.revision.ObjectId) ModuleIdProvider(com.b2international.snowowl.snomed.datastore.request.ModuleRequest.ModuleIdProvider) ServiceProvider(com.b2international.snowowl.core.ServiceProvider) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) RevisionDiff(com.b2international.index.revision.StagingArea.RevisionDiff) IOException(java.io.IOException)

Example 9 with ServiceProvider

use of com.b2international.snowowl.core.ServiceProvider 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 10 with ServiceProvider

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

the class ServerInfoGetRequest method execute.

@Override
public ServerInfo execute(ServiceProvider context) {
    final Version version = Platform.getBundle(CoreActivator.PLUGIN_ID).getVersion();
    final String description = context.service(SnowOwlConfiguration.class).getDescription();
    final Repositories repositories = RepositoryRequests.prepareSearch().build().execute(context);
    final Set<String> repositoryIndices = repositories.stream().map(RepositoryInfo::indices).flatMap(List::stream).map(EsIndexStatus::getIndex).collect(Collectors.toSet());
    // this represents the current full cluster status with all global and terminology plugin specific indices
    EsClusterStatus clusterStatus = context.service(EsClient.class).status();
    // append global indices to the server info response
    final List<EsIndexStatus> globalIndices = clusterStatus.getIndices().stream().filter(indexStatus -> !repositoryIndices.contains(indexStatus.getIndex())).collect(Collectors.toList());
    EsClusterStatus globalStatus = new EsClusterStatus(clusterStatus.isAvailable(), clusterStatus.getDiagnosis(), globalIndices);
    return new ServerInfo(version.toString(), description, repositories, globalStatus);
}
Also used : Repositories(com.b2international.snowowl.core.Repositories) EsClient(com.b2international.index.es.client.EsClient) EsClusterStatus(com.b2international.index.es.client.EsClusterStatus) Request(com.b2international.snowowl.core.events.Request) Set(java.util.Set) ServerInfo(com.b2international.snowowl.core.ServerInfo) Unprotected(com.b2international.snowowl.core.authorization.Unprotected) Version(org.osgi.framework.Version) Collectors(java.util.stream.Collectors) RepositoryRequests(com.b2international.snowowl.core.repository.RepositoryRequests) RepositoryInfo(com.b2international.snowowl.core.RepositoryInfo) List(java.util.List) EsIndexStatus(com.b2international.index.es.client.EsIndexStatus) CoreActivator(com.b2international.snowowl.core.CoreActivator) ServiceProvider(com.b2international.snowowl.core.ServiceProvider) Platform(org.eclipse.core.runtime.Platform) SnowOwlConfiguration(com.b2international.snowowl.core.config.SnowOwlConfiguration) Repositories(com.b2international.snowowl.core.Repositories) EsIndexStatus(com.b2international.index.es.client.EsIndexStatus) Version(org.osgi.framework.Version) ServerInfo(com.b2international.snowowl.core.ServerInfo) EsClusterStatus(com.b2international.index.es.client.EsClusterStatus) List(java.util.List) EsClient(com.b2international.index.es.client.EsClient) SnowOwlConfiguration(com.b2international.snowowl.core.config.SnowOwlConfiguration)

Aggregations

ServiceProvider (com.b2international.snowowl.core.ServiceProvider)16 List (java.util.List)9 Collectors (java.util.stream.Collectors)9 Set (java.util.Set)8 IOException (java.io.IOException)6 ResourceURI (com.b2international.snowowl.core.ResourceURI)5 Map (java.util.Map)5 Options (com.b2international.commons.options.Options)4 BadRequestException (com.b2international.commons.exceptions.BadRequestException)3 RepositoryManager (com.b2international.snowowl.core.RepositoryManager)3 CodeSystemRequests (com.b2international.snowowl.core.codesystem.CodeSystemRequests)3 Request (com.b2international.snowowl.core.events.Request)3 User (com.b2international.snowowl.core.identity.User)3 ApiException (com.b2international.commons.exceptions.ApiException)2 Branch (com.b2international.snowowl.core.branch.Branch)2 Concept (com.b2international.snowowl.core.domain.Concept)2 ConceptMapMappings (com.b2international.snowowl.core.domain.ConceptMapMappings)2 RequestHeaders (com.b2international.snowowl.core.events.util.RequestHeaders)2 Permission (com.b2international.snowowl.core.identity.Permission)2 IEventBus (com.b2international.snowowl.eventbus.IEventBus)2