Search in sources :

Example 36 with SnowowlRuntimeException

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);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) HttpGet(org.apache.http.client.methods.HttpGet) IOException(java.io.IOException) ImmutableMap(com.google.common.collect.ImmutableMap) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) SctId(com.b2international.snowowl.snomed.cis.domain.SctId)

Example 37 with SnowowlRuntimeException

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);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpGet(org.apache.http.client.methods.HttpGet) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) SctId(com.b2international.snowowl.snomed.cis.domain.SctId)

Example 38 with SnowowlRuntimeException

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();
    }
}
Also used : IndexException(com.b2international.index.IndexException) CycleDetectedException(com.b2international.commons.exceptions.CycleDetectedException) Locks(com.b2international.snowowl.core.locks.Locks) IOperationLockManager(com.b2international.snowowl.core.locks.IOperationLockManager) DatastoreLockTarget(com.b2international.snowowl.core.internal.locks.DatastoreLockTarget) DatastoreLockContext(com.b2international.snowowl.core.internal.locks.DatastoreLockContext) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException)

Example 39 with SnowowlRuntimeException

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();
    }
}
Also used : SnomedConcept(com.b2international.snowowl.snomed.core.domain.SnomedConcept) Notifications(com.b2international.snowowl.core.events.Notifications) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) ClassificationRequests(com.b2international.snowowl.snomed.reasoner.request.ClassificationRequests) BlockingQueue(java.util.concurrent.BlockingQueue) RemoteJobEntry(com.b2international.snowowl.core.jobs.RemoteJobEntry) IEventBus(com.b2international.snowowl.eventbus.IEventBus) UUID(java.util.UUID) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) IDs(com.b2international.snowowl.core.id.IDs) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) DatastoreLockContextDescriptions(com.b2international.snowowl.core.internal.locks.DatastoreLockContextDescriptions) RemoteJobNotification(com.b2international.snowowl.core.jobs.RemoteJobNotification) Environment(com.b2international.snowowl.core.setup.Environment) Queues(com.google.common.collect.Queues) DisposableObserver(io.reactivex.observers.DisposableObserver) ApplicationContext.getServiceForClass(com.b2international.snowowl.core.ApplicationContext.getServiceForClass) JobRequests(com.b2international.snowowl.core.jobs.JobRequests) RemoteJobs(com.b2international.snowowl.core.jobs.RemoteJobs) Optional(java.util.Optional) Observable(io.reactivex.Observable) ApplicationContext(com.b2international.snowowl.core.ApplicationContext) RemoteJobs(com.b2international.snowowl.core.jobs.RemoteJobs) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) RemoteJobEntry(com.b2international.snowowl.core.jobs.RemoteJobEntry) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) Environment(com.b2international.snowowl.core.setup.Environment) Notifications(com.b2international.snowowl.core.events.Notifications)

Aggregations

SnowowlRuntimeException (com.b2international.snowowl.core.api.SnowowlRuntimeException)39 IOException (java.io.IOException)27 SctId (com.b2international.snowowl.snomed.cis.domain.SctId)7 Collection (java.util.Collection)7 HttpPost (org.apache.http.client.methods.HttpPost)6 BadRequestException (com.b2international.commons.exceptions.BadRequestException)5 RevisionSearcher (com.b2international.index.revision.RevisionSearcher)4 Promise (com.b2international.snowowl.core.events.util.Promise)4 JsonNode (com.fasterxml.jackson.databind.JsonNode)4 List (java.util.List)4 TimeUnit (java.util.concurrent.TimeUnit)4 File (java.io.File)3 Path (java.nio.file.Path)3 NamingException (javax.naming.NamingException)3 InitialLdapContext (javax.naming.ldap.InitialLdapContext)3 HttpGet (org.apache.http.client.methods.HttpGet)3 Logger (org.slf4j.Logger)3 JwkException (com.auth0.jwk.JwkException)2 JwkProvider (com.auth0.jwk.JwkProvider)2 JwkProviderBuilder (com.auth0.jwk.JwkProviderBuilder)2