Search in sources :

Example 1 with ApiException

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

the class RemoteJob method run.

@Override
protected final IStatus run(IProgressMonitor monitor) {
    final ObjectMapper mapper = this.context.service(ObjectMapper.class);
    final IProgressMonitor trackerMonitor = this.context.service(RemoteJobTracker.class).createMonitor(id, monitor);
    try {
        // override user when necessary
        User user = context.service(User.class);
        if (User.isSystem(this.user)) {
            user = User.SYSTEM;
        } else if (!user.getUsername().equals(this.user)) {
            user = UserRequests.prepareGet(this.user).build().execute(this.context);
        }
        // seed the monitor instance into the current context, so the request can use it for progress reporting
        final ServiceProvider context = this.context.inject().bind(IProgressMonitor.class, trackerMonitor).bind(RemoteJob.class, this).bind(User.class, user).build();
        final Object response = request.execute(context);
        if (response != null) {
            final Class<? extends Object> responseType = response.getClass();
            if (Primitives.isWrapperType(responseType) || String.class.isAssignableFrom(responseType) || UUID.class.isAssignableFrom(responseType)) {
                this.response = toJson(mapper, ImmutableMap.of("value", response));
            } else {
                this.response = toJson(mapper, response);
            }
        }
        final IStatus status = (IStatus) getProperty(REQUEST_STATUS);
        return (status != null) ? status : Statuses.ok();
    } catch (OperationCanceledException e) {
        return Statuses.cancel();
    } catch (Throwable e) {
        final ApiError apiError;
        if (e instanceof ApiException) {
            apiError = ((ApiException) e).toApiError();
        } else {
            apiError = ApiError.builder(e.getMessage()).status(500).developerMessage("Exception caught while executing request in remote job.").addInfo("exception-class", e.getClass().getSimpleName()).build();
        }
        this.response = toJson(mapper, apiError);
        // XXX: Don't delete remote jobs with errors
        autoClean = false;
        return Statuses.error(CoreActivator.PLUGIN_ID, "Failed to execute long running request", e);
    } finally {
        if (autoClean) {
            context.service(RemoteJobTracker.class).requestDeletes(Collections.singleton(id));
        }
    }
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) User(com.b2international.snowowl.core.identity.User) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) ServiceProvider(com.b2international.snowowl.core.ServiceProvider) ApiError(com.b2international.commons.exceptions.ApiError) UUID(java.util.UUID) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ApiException(com.b2international.commons.exceptions.ApiException)

Example 2 with ApiException

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

the class ResourcesImportRequest method execute.

@Override
public ImportResponse execute(ServiceProvider context) {
    final InternalAttachmentRegistry attachmentRegistry = (InternalAttachmentRegistry) context.service(AttachmentRegistry.class);
    final File file = attachmentRegistry.getAttachment(sourceFile.getAttachmentId());
    try {
        final List<R> sourceFileContent = loadSourceFileContent(context, file);
        final Map<String, R> existingResources = newHashMap(loadExistingResources(context, sourceFileContent));
        final ImportDefectAcceptor defectAcceptor = new ImportDefectAcceptor(sourceFile.getFileName());
        validateSourceFileContent(context, sourceFileContent, existingResources, defectAcceptor);
        List<ImportDefect> defects = defectAcceptor.getDefects();
        // Content with validation errors can not be imported
        ImportResponse validationResponse = ImportResponse.defects(defects);
        if (!validationResponse.getErrors().isEmpty()) {
            return validationResponse;
        }
        final Set<ComponentURI> visitedComponents = Sets.newHashSet();
        // Import each resource present in the source file, along with its content
        for (final R resource : sourceFileContent) {
            final String id = resource.getId();
            ComponentURI importedResource = importResource(context, resource, existingResources.get(id));
            if (importedResource != null) {
                visitedComponents.add(importedResource);
            }
            visitedComponents.addAll(importContent(context, resource, existingResources.get(id)));
        }
        return ImportResponse.success(visitedComponents, defects);
    } catch (final ApiException e) {
        throw e;
    } catch (final Exception e) {
        String error = "Unexpected error happened during the import of the source file: " + sourceFile.getFileName();
        context.log().error(error, e);
        return ImportResponse.error(error);
    } finally {
        if (sourceFile != null && attachmentRegistry != null) {
            attachmentRegistry.delete(sourceFile.getAttachmentId());
        }
    }
}
Also used : InternalAttachmentRegistry(com.b2international.snowowl.core.attachments.InternalAttachmentRegistry) InternalAttachmentRegistry(com.b2international.snowowl.core.attachments.InternalAttachmentRegistry) AttachmentRegistry(com.b2international.snowowl.core.attachments.AttachmentRegistry) ComponentURI(com.b2international.snowowl.core.uri.ComponentURI) ApiException(com.b2international.commons.exceptions.ApiException) File(java.io.File) ApiException(com.b2international.commons.exceptions.ApiException)

Example 3 with ApiException

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

the class SnomedOWLExpressionConverter method toSnomedOWLRelationships.

public SnomedOWLExpressionConverterResult toSnomedOWLRelationships(String conceptId, String axiomExpression) {
    // Only attempt to convert axioms which the OWL toolkit supports
    if (Strings.isNullOrEmpty(axiomExpression) || !isAxiomSupported(axiomExpression)) {
        return SnomedOWLExpressionConverterResult.EMPTY;
    }
    try {
        final Long conceptIdLong = Long.valueOf(conceptId);
        final AxiomRepresentation axiomRepresentation = convertAxiom(conceptId, axiomExpression);
        if (axiomRepresentation == null) {
            return SnomedOWLExpressionConverterResult.EMPTY;
        }
        boolean gci = false;
        Map<Integer, List<Relationship>> relationships = null;
        if (conceptIdLong.equals(axiomRepresentation.getLeftHandSideNamedConcept())) {
            relationships = axiomRepresentation.getRightHandSideRelationships();
        } else if (conceptIdLong.equals(axiomRepresentation.getRightHandSideNamedConcept())) {
            /*
				 * XXX: EquivalentClasses axioms are not ordered in any meaningful way, so it
				 * can happen that the class expression representing relationships falls on the left-hand side
				 */
            gci = axiomRepresentation.isPrimitive();
            relationships = axiomRepresentation.getLeftHandSideRelationships();
        } else {
            LOG.warn("Illegal assignment of referenced component id ('{}') was detected for the OWL expression: '{}'", conceptId, axiomExpression);
        }
        if (relationships == null) {
            return SnomedOWLExpressionConverterResult.EMPTY;
        }
        final List<SnomedOWLRelationshipDocument> convertedRelationships = relationships.values().stream().flatMap(List::stream).map(relationship -> {
            if (relationship.isConcrete()) {
                return SnomedOWLRelationshipDocument.createValue(Long.toString(relationship.getTypeId()), toRelationshipValue(relationship.getValue()), relationship.getGroup());
            } else {
                return SnomedOWLRelationshipDocument.create(Long.toString(relationship.getTypeId()), Long.toString(relationship.getDestinationId()), relationship.getGroup());
            }
        }).collect(Collectors.toList());
        return new SnomedOWLExpressionConverterResult(gci ? null : convertedRelationships, gci ? convertedRelationships : null);
    } catch (ApiException e) {
        throw e;
    } catch (Exception e) {
        LOG.error("Failed to convert OWL axiom '{}' to relationship representations for concept '{}'", axiomExpression, conceptId, e);
        return SnomedOWLExpressionConverterResult.EMPTY;
    }
}
Also used : RelationshipValueType(com.b2international.snowowl.snomed.core.domain.RelationshipValueType) SnomedRefSetMemberIndexEntry(com.b2international.snowowl.snomed.datastore.index.entry.SnomedRefSetMemberIndexEntry) Stopwatch(com.google.common.base.Stopwatch) ConversionException(org.snomed.otf.owltoolkit.conversion.ConversionException) LoggerFactory(org.slf4j.LoggerFactory) Supplier(com.google.common.base.Supplier) Callable(java.util.concurrent.Callable) TimeUtil(com.b2international.commons.time.TimeUtil) BigDecimal(java.math.BigDecimal) AxiomRepresentation(org.snomed.otf.owltoolkit.domain.AxiomRepresentation) Strings(com.google.common.base.Strings) Options(com.b2international.commons.options.Options) Map(java.util.Map) Suppliers(com.google.common.base.Suppliers) SnomedOWLRelationshipDocument(com.b2international.snowowl.snomed.datastore.index.entry.SnomedOWLRelationshipDocument) ConcreteValue(org.snomed.otf.owltoolkit.domain.Relationship.ConcreteValue) ApiException(com.b2international.commons.exceptions.ApiException) SnomedReferenceSetMembers(com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMembers) AxiomRelationshipConversionService(org.snomed.otf.owltoolkit.conversion.AxiomRelationshipConversionService) Logger(org.slf4j.Logger) RelationshipValue(com.b2international.snowowl.snomed.core.domain.RelationshipValue) Set(java.util.Set) Collectors(java.util.stream.Collectors) List(java.util.List) SnomedCoreComponent(com.b2international.snowowl.snomed.core.domain.SnomedCoreComponent) SnomedReferenceSetMember(com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMember) Relationship(org.snomed.otf.owltoolkit.domain.Relationship) BranchContext(com.b2international.snowowl.core.domain.BranchContext) SnomedRefSetType(com.b2international.snowowl.snomed.core.domain.refset.SnomedRefSetType) SnomedOWLRelationshipDocument(com.b2international.snowowl.snomed.datastore.index.entry.SnomedOWLRelationshipDocument) List(java.util.List) AxiomRepresentation(org.snomed.otf.owltoolkit.domain.AxiomRepresentation) ConversionException(org.snomed.otf.owltoolkit.conversion.ConversionException) ApiException(com.b2international.commons.exceptions.ApiException) ApiException(com.b2international.commons.exceptions.ApiException)

Example 4 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 5 with ApiException

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

the class AbstractBranchChangeRequest method execute.

@Override
public Merge execute(RepositoryContext context) {
    try {
        final Branch source = RepositoryRequests.branching().prepareGet(sourcePath).build().execute(context);
        final Branch target = RepositoryRequests.branching().prepareGet(targetPath).build().execute(context);
        Merge merge = Merge.builder().source(sourcePath).target(targetPath).build();
        try {
            Commit commit = applyChanges(context, source, target);
            if (commit != null) {
                context.service(RepositoryCommitNotificationSender.class).publish(context, commit);
            }
            return merge.completed();
        } catch (BranchMergeConflictException e) {
            return merge.failedWithConflicts(e.getMessage(), toMergeConflicts(e.getConflicts()));
        } catch (ApiException e) {
            return merge.failed(e.toApiError());
        } catch (RuntimeException e) {
            context.log().error("Failed to merge {} into {}", sourcePath, targetPath, e);
            return merge.failed(ApiError.of(e.getMessage()));
        }
    } catch (NotFoundException e) {
        throw e.toBadRequestException();
    }
}
Also used : Merge(com.b2international.snowowl.core.merge.Merge) RepositoryCommitNotificationSender(com.b2international.snowowl.core.repository.RepositoryCommitNotificationSender) NotFoundException(com.b2international.commons.exceptions.NotFoundException) 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