Search in sources :

Example 6 with ApiException

use of com.b2international.commons.exceptions.ApiException in project snow-owl by b2ihealthcare.

the class ApiRequestHandler method handle.

@Override
public final void handle(IMessage message) {
    try {
        final Request<ServiceProvider, ?> req = message.body(Request.class, classLoader);
        final ResponseHeaders responseHeaders = new ResponseHeaders();
        final ServiceProvider executionContext = context.inject().bind(RequestHeaders.class, new RequestHeaders(message.headers())).bind(ResponseHeaders.class, responseHeaders).build();
        // monitor each request execution
        final Object body = new MonitoredRequest<>(// authorize each request execution
        new AuthorizedRequest<>(// rate limit all requests
        new RateLimitingRequest<>(// actual request
        req))).execute(executionContext);
        if (body == null) {
            LoggerFactory.getLogger(ApiRequestHandler.class).error("No response was returned from request: " + req.getClass());
        }
        message.reply(body, responseHeaders.headers());
    } catch (WrappedException e) {
        message.fail(e.getCause());
    } catch (ApiException e) {
        message.fail(e);
    } catch (Throwable e) {
        LoggerFactory.getLogger(ApiRequestHandler.class).error("Unexpected error when executing request:", e);
        message.fail(e);
    }
}
Also used : WrappedException(org.eclipse.emf.common.util.WrappedException) AuthorizedRequest(com.b2international.snowowl.core.authorization.AuthorizedRequest) ServiceProvider(com.b2international.snowowl.core.ServiceProvider) ResponseHeaders(com.b2international.snowowl.core.events.util.ResponseHeaders) RequestHeaders(com.b2international.snowowl.core.events.util.RequestHeaders) ApiException(com.b2international.commons.exceptions.ApiException)

Example 7 with ApiException

use of com.b2international.commons.exceptions.ApiException in project snow-owl by b2ihealthcare.

the class SnomedEclLabelerRequest method execute.

@Override
public LabeledEclExpressions execute(BranchContext context) {
    final EclSerializer eclSerializer = context.service(EclSerializer.class);
    final EclParser eclParser = context.service(EclParser.class);
    final Set<String> conceptIdsToLabel = Sets.newHashSetWithExpectedSize(expressions.size());
    final Map<String, ExpressionConstraint> queries = Maps.newHashMapWithExpectedSize(expressions.size());
    final LinkedHashMap<String, Object> errors = Maps.newLinkedHashMap();
    for (String expression : expressions) {
        if (Strings.isNullOrEmpty(expression)) {
            continue;
        }
        try {
            ExpressionConstraint query = queries.computeIfAbsent(expression, (key) -> eclParser.parse(key));
            conceptIdsToLabel.addAll(collect(query));
        } catch (ApiException e) {
            if (e instanceof SyntaxException) {
                errors.put(expression, List.copyOf(((SyntaxException) e).getAdditionalInfo().values()));
            } else if (e instanceof BadRequestException) {
                errors.put(expression, e.getMessage());
            } else {
                throw e;
            }
        }
    }
    if (!errors.isEmpty()) {
        BadRequestException badRequestException = new BadRequestException("One or more ECL syntax errors");
        badRequestException.withAdditionalInfo("erroneousExpressions", errors);
        throw badRequestException;
    }
    // fetch all concept labels
    final Map<String, String> labels = SnomedRequests.prepareSearchConcept().filterByIds(conceptIdsToLabel).setLimit(conceptIdsToLabel.size()).setExpand(descriptionType.toLowerCase() + "()").setLocales(locales()).build().execute(context).stream().collect(Collectors.toMap(SnomedConcept::getId, this::extractLabel));
    // expand all queries with labels
    List<String> results = expressions.stream().map(expression -> {
        if (Strings.isNullOrEmpty(expression)) {
            return expression;
        } else {
            ExpressionConstraint query = queries.get(expression);
            expand(query, labels);
            return eclSerializer.serialize(query);
        }
    }).collect(Collectors.toList());
    return new LabeledEclExpressions(results);
}
Also used : ExpressionConstraint(com.b2international.snomed.ecl.ecl.ExpressionConstraint) BadRequestException(com.b2international.commons.exceptions.BadRequestException) SnomedConcept(com.b2international.snowowl.snomed.core.domain.SnomedConcept) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) java.util(java.util) EObjectWalker(com.b2international.snowowl.core.emf.EObjectWalker) EObjectTreeNode(com.b2international.snowowl.core.emf.EObjectTreeNode) NotNull(javax.validation.constraints.NotNull) Collectors(java.util.stream.Collectors) Maps(com.google.common.collect.Maps) Sets(com.google.common.collect.Sets) Strings(com.google.common.base.Strings) SnomedRequests(com.b2international.snowowl.snomed.datastore.request.SnomedRequests) NotEmpty(org.hibernate.validator.constraints.NotEmpty) AccessControl(com.b2international.snowowl.core.authorization.AccessControl) SyntaxException(com.b2international.commons.exceptions.SyntaxException) Permission(com.b2international.snowowl.core.identity.Permission) EclConceptReference(com.b2international.snomed.ecl.ecl.EclConceptReference) ExpressionConstraint(com.b2international.snomed.ecl.ecl.ExpressionConstraint) BranchContext(com.b2international.snowowl.core.domain.BranchContext) NoopTreeVisitor(com.b2international.commons.tree.NoopTreeVisitor) ApiException(com.b2international.commons.exceptions.ApiException) ResourceRequest(com.b2international.snowowl.core.request.ResourceRequest) SyntaxException(com.b2international.commons.exceptions.SyntaxException) BadRequestException(com.b2international.commons.exceptions.BadRequestException) ApiException(com.b2international.commons.exceptions.ApiException)

Example 8 with ApiException

use of com.b2international.commons.exceptions.ApiException in project snow-owl by b2ihealthcare.

the class SnomedRf2ImportRequest method execute.

@Override
public ImportResponse execute(BranchContext context) {
    log = LoggerFactory.getLogger("import");
    context = context.inject().bind(Logger.class, log).build();
    Rf2ImportConfiguration importConfig = new Rf2ImportConfiguration(releaseType, createVersions);
    validate(context, importConfig);
    final InternalAttachmentRegistry fileReg = (InternalAttachmentRegistry) context.service(AttachmentRegistry.class);
    final File rf2Archive = fileReg.getAttachment(this.rf2Archive.getAttachmentId());
    try (Locks locks = Locks.on(context).lock(DatastoreLockContextDescriptions.IMPORT)) {
        return doImport(context, rf2Archive, importConfig);
    } catch (Exception e) {
        if (e instanceof ApiException) {
            throw (ApiException) e;
        }
        throw SnowowlRuntimeException.wrap(e);
    }
}
Also used : InternalAttachmentRegistry(com.b2international.snowowl.core.attachments.InternalAttachmentRegistry) AttachmentRegistry(com.b2international.snowowl.core.attachments.AttachmentRegistry) InternalAttachmentRegistry(com.b2international.snowowl.core.attachments.InternalAttachmentRegistry) Locks(com.b2international.snowowl.core.locks.Locks) ZipFile(java.util.zip.ZipFile) File(java.io.File) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) ApiException(com.b2international.commons.exceptions.ApiException) BadRequestException(com.b2international.commons.exceptions.BadRequestException) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ApiException(com.b2international.commons.exceptions.ApiException)

Example 9 with ApiException

use of com.b2international.commons.exceptions.ApiException in project snow-owl by b2ihealthcare.

the class ImportRequest method doExecute.

@Override
public final ImportResponse doExecute(TransactionContext context) {
    context.log().info("Importing components from source file '{}'.", this.attachment.getFileName());
    InternalAttachmentRegistry iar = null;
    try {
        iar = (InternalAttachmentRegistry) context.service(AttachmentRegistry.class);
        File attachment = iar.getAttachment(this.attachment.getAttachmentId());
        ImportDefectAcceptor defectsAcceptor = new ImportDefectAcceptor(this.attachment.getFileName());
        doValidate(context, attachment, defectsAcceptor, context.service(IProgressMonitor.class));
        final ImportResponse validationResponse = ImportResponse.defects(defectsAcceptor.getDefects());
        if (!validationResponse.getErrors().isEmpty()) {
            return validationResponse;
        } else {
            final Set<ComponentURI> visitedComponents = Sets.newHashSet();
            doImport(context, attachment, visitedComponents::add, context.service(IProgressMonitor.class));
            context.log().info("Finished importing components from source file '{}'.", this.attachment.getFileName());
            return ImportResponse.success(visitedComponents, validationResponse.getDefects());
        }
    } catch (ApiException e) {
        throw e;
    } catch (Exception e) {
        String error = "Unexpected error happened during the import of the source file: " + attachment.getFileName();
        context.log().error(error, e);
        return ImportResponse.error(error);
    } finally {
        if (attachment != null && iar != null) {
            iar.delete(attachment.getAttachmentId());
        }
    }
}
Also used : InternalAttachmentRegistry(com.b2international.snowowl.core.attachments.InternalAttachmentRegistry) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) ComponentURI(com.b2international.snowowl.core.uri.ComponentURI) File(java.io.File) ApiException(com.b2international.commons.exceptions.ApiException) ApiException(com.b2international.commons.exceptions.ApiException)

Example 10 with ApiException

use of com.b2international.commons.exceptions.ApiException in project snow-owl by b2ihealthcare.

the class TransactionalRequest method execute.

@Override
public CommitResult execute(BranchContext context) {
    // final Metrics metrics = context.service(Metrics.class);
    // metrics.setExternalValue("preRequest", preRequestPreparationTime);
    TransactionContext tx = null;
    try (final TransactionContext transaction = context.openTransaction(context, author, commitComment, parentLockContext)) {
        tx = transaction;
        transaction.setNotificationEnabled(notify);
        final Object body = executeNext(transaction);
        return commit(transaction, body);
    } catch (ApiException e) {
        if (tx != null) {
            tx.rollback();
        }
        throw e;
    } catch (Exception e) {
        if (tx != null) {
            tx.rollback();
        }
        throw SnowowlRuntimeException.wrap(e);
    }
}
Also used : TransactionContext(com.b2international.snowowl.core.domain.TransactionContext) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) ApiException(com.b2international.commons.exceptions.ApiException) ApiException(com.b2international.commons.exceptions.ApiException)

Aggregations

ApiException (com.b2international.commons.exceptions.ApiException)10 SnowowlRuntimeException (com.b2international.snowowl.core.api.SnowowlRuntimeException)3 InternalAttachmentRegistry (com.b2international.snowowl.core.attachments.InternalAttachmentRegistry)3 File (java.io.File)3 BadRequestException (com.b2international.commons.exceptions.BadRequestException)2 ServiceProvider (com.b2international.snowowl.core.ServiceProvider)2 AttachmentRegistry (com.b2international.snowowl.core.attachments.AttachmentRegistry)2 BranchContext (com.b2international.snowowl.core.domain.BranchContext)2 ComponentURI (com.b2international.snowowl.core.uri.ComponentURI)2 Strings (com.google.common.base.Strings)2 Collectors (java.util.stream.Collectors)2 IProgressMonitor (org.eclipse.core.runtime.IProgressMonitor)2 ApiError (com.b2international.commons.exceptions.ApiError)1 NotFoundException (com.b2international.commons.exceptions.NotFoundException)1 SyntaxException (com.b2international.commons.exceptions.SyntaxException)1 Options (com.b2international.commons.options.Options)1 TimeUtil (com.b2international.commons.time.TimeUtil)1 NoopTreeVisitor (com.b2international.commons.tree.NoopTreeVisitor)1 EclConceptReference (com.b2international.snomed.ecl.ecl.EclConceptReference)1 ExpressionConstraint (com.b2international.snomed.ecl.ecl.ExpressionConstraint)1