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);
}
}
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();
}
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));
}
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);
}
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);
}
Aggregations