use of com.b2international.snowowl.core.api.SnowowlRuntimeException in project snow-owl by b2ihealthcare.
the class CisSnomedIdentifierService method readSctIds.
private Map<String, SctId> readSctIds(final Set<String> componentIds) {
if (CompareUtils.isEmpty(componentIds)) {
return Collections.emptyMap();
}
HttpPost bulkRequest = null;
HttpGet singleRequest = null;
try {
if (componentIds.size() > 1) {
LOGGER.debug("Sending bulk component ID get request.");
final ImmutableMap.Builder<String, SctId> resultBuilder = ImmutableMap.builder();
for (final Collection<String> ids : Iterables.partition(componentIds, requestBulkLimit)) {
final String idsAsString = Joiner.on(',').join(ids);
final ObjectNode idsAsJson = mapper.createObjectNode().put("sctids", idsAsString);
bulkRequest = client.httpPost(String.format("sct/bulk/ids/?token=%s", getToken()), idsAsJson);
final String response = execute(bulkRequest);
final SctId[] sctIds = mapper.readValue(response, SctId[].class);
final Map<String, SctId> sctIdMap = Maps.uniqueIndex(Arrays.asList(sctIds), SctId::getSctid);
resultBuilder.putAll(sctIdMap);
}
return resultBuilder.build();
} else {
final String componentId = Iterables.getOnlyElement(componentIds);
LOGGER.debug("Sending component ID {} get request.", componentId);
singleRequest = httpGet(String.format("sct/ids/%s?token=%s", componentId, getToken()));
final String response = execute(singleRequest);
final SctId sctId = mapper.readValue(response, SctId.class);
return ImmutableMap.of(sctId.getSctid(), sctId);
}
} catch (IOException e) {
throw new SnowowlRuntimeException("Exception while getting IDs.", e);
} finally {
release(bulkRequest);
release(singleRequest);
}
}
use of com.b2international.snowowl.core.api.SnowowlRuntimeException in project snow-owl by b2ihealthcare.
the class CisSnomedIdentifierService method generateSctIds.
@Override
public Map<String, SctId> generateSctIds(String namespace, ComponentCategory category, int quantity) {
checkNotNull(category, "Component category must not be null.");
checkArgument(quantity > 0, "Number of requested IDs should be non-negative.");
checkCategory(category);
LOGGER.debug("Generating {} component IDs for category {}.", quantity, category.getDisplayName());
HttpPost generateRequest = null;
HttpGet recordsRequest = null;
try {
if (quantity > 1) {
LOGGER.debug("Sending {} ID bulk generation request.", category.getDisplayName());
generateRequest = httpPost(String.format("sct/bulk/generate?token=%s", getToken()), createBulkGenerationData(namespace, category, quantity));
final String response = execute(generateRequest);
final String jobId = mapper.readValue(response, JsonNode.class).get("id").asText();
joinBulkJobPolling(jobId, quantity, getToken());
recordsRequest = httpGet(String.format("bulk/jobs/%s/records?token=%s", jobId, getToken()));
final String recordsResponse = execute(recordsRequest);
final JsonNode[] records = mapper.readValue(recordsResponse, JsonNode[].class);
return readSctIds(getComponentIds(records));
} else {
LOGGER.debug("Sending {} ID single generation request.", category.getDisplayName());
generateRequest = httpPost(String.format("sct/generate?token=%s", getToken()), createGenerationData(namespace, category));
final String response = execute(generateRequest);
final SctId sctid = mapper.readValue(response, SctId.class);
return readSctIds(Collections.singleton(sctid.getSctid()));
}
} catch (IOException e) {
throw new SnowowlRuntimeException("Caught exception while generating IDs.", e);
} finally {
release(generateRequest);
release(recordsRequest);
}
}
use of com.b2international.snowowl.core.api.SnowowlRuntimeException in project snow-owl by b2ihealthcare.
the class RepositoryTransactionContext method commit.
@Override
public Optional<Commit> commit(String author, String commitComment, String parentLockContext) {
if (!isDirty()) {
return Optional.empty();
}
// fall back to the current lock context or ROOT if none is present
if (Strings.isNullOrEmpty(parentLockContext)) {
parentLockContext = optionalService(Locks.class).map(Locks::lockContext).orElse(DatastoreLockContextDescriptions.ROOT);
}
final DatastoreLockContext lockContext = createLockContext(service(User.class).getUsername(), parentLockContext);
final DatastoreLockTarget lockTarget = createLockTarget(info().id(), path());
IOperationLockManager locks = service(IOperationLockManager.class);
Commit commit = null;
try {
locks.lock(lockContext, 1000L, lockTarget);
final long timestamp = service(TimestampProvider.class).getTimestamp();
log().info("Persisting changes to {}@{}", path(), timestamp);
commit = staging.commit(null, timestamp, author, commitComment);
log().info("Changes have been successfully persisted to {}@{}.", path(), timestamp);
return Optional.ofNullable(commit);
} catch (final IndexException e) {
Throwable rootCause = Throwables.getRootCause(e);
if (rootCause instanceof CycleDetectedException) {
throw (CycleDetectedException) rootCause;
}
throw new SnowowlRuntimeException(e.getMessage(), e);
} finally {
locks.unlock(lockContext, lockTarget);
if (commit != null && isNotificationEnabled()) {
service(RepositoryCommitNotificationSender.class).publish(this, commit);
}
clear();
}
}
use of com.b2international.snowowl.core.api.SnowowlRuntimeException in project snow-owl by b2ihealthcare.
the class ClassifyOperation method run.
/**
* Allocates a reasoner instance, performs the requested operation, then releases the borrowed instance back to the pool.
* @param monitor an {@link IProgressMonitor} to monitor operation progress
* @return the value returned by {@link #processResults(IProgressMonitor, long)}
* @throws OperationCanceledException
*/
public T run(final IProgressMonitor monitor) throws OperationCanceledException {
monitor.beginTask("Classification in progress...", IProgressMonitor.UNKNOWN);
try {
final String classificationId = UUID.randomUUID().toString();
final String jobId = IDs.sha1(classificationId);
final Notifications notifications = getServiceForClass(Notifications.class);
final BlockingQueue<RemoteJobEntry> jobQueue = Queues.newArrayBlockingQueue(1);
final Observable<RemoteJobEntry> jobObservable = notifications.ofType(RemoteJobNotification.class).filter(RemoteJobNotification::isChanged).filter(notification -> notification.getJobIds().contains(jobId)).concatMap(notification -> JobRequests.prepareSearch().one().filterById(jobId).buildAsync().execute(getEventBus())).map(RemoteJobs::first).map(Optional<RemoteJobEntry>::get).filter(RemoteJobEntry::isDone);
// "One-shot" subscription; it should self-destruct after the first notification
jobObservable.subscribe(new DisposableObserver<RemoteJobEntry>() {
@Override
public void onComplete() {
dispose();
}
@Override
public void onError(final Throwable t) {
dispose();
}
@Override
public void onNext(final RemoteJobEntry job) {
try {
jobQueue.put(job);
} catch (InterruptedException e) {
throw new SnowowlRuntimeException("Interrupted while trying to add a remote job entry to the queue.", e);
} finally {
dispose();
}
}
});
ClassificationRequests.prepareCreateClassification().setClassificationId(classificationId).setReasonerId(reasonerId).setUserId(userId).addAllConcepts(additionalConcepts).setParentLockContext(parentLockContext).build(branch).get(ApplicationContext.getServiceForClass(Environment.class));
while (true) {
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
try {
final RemoteJobEntry jobEntry = jobQueue.poll(CHECK_JOB_INTERVAL_SECONDS, TimeUnit.SECONDS);
if (jobEntry == null) {
continue;
}
switch(jobEntry.getState()) {
// $FALL-THROUGH$
case SCHEDULED:
case RUNNING:
case CANCEL_REQUESTED:
break;
case FINISHED:
try {
return processResults(classificationId);
} finally {
deleteEntry(jobId);
}
case CANCELED:
deleteEntry(jobId);
throw new OperationCanceledException();
case FAILED:
deleteEntry(jobId);
throw new SnowowlRuntimeException("Failed to retrieve the results of the classification.");
default:
throw new IllegalStateException("Unexpected state '" + jobEntry.getState() + "'.");
}
} catch (final InterruptedException e) {
// Nothing to do
}
}
} finally {
monitor.done();
}
}
Aggregations