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