Search in sources :

Example 26 with BadRequestException

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

the class ConceptMapCompareDsvExportRequest method execute.

@Override
public File execute(ServiceProvider context) {
    final List<ConceptMapCompareResultItem> resultsToExport = items.stream().filter(item -> changeKinds.contains(item.getChangeKind())).collect(Collectors.toList());
    final CsvMapper mapper = new CsvMapper();
    final CsvSchema schema = mapper.schemaFor(ConceptMapCompareResultItem.class).withHeader().withoutQuoteChar().withColumnSeparator(delimiter).withNullValue("");
    try (OutputStream newOutputStream = Files.newOutputStream(Paths.get(filePath), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
        mapper.writer(schema).writeValue(newOutputStream, resultsToExport);
    } catch (Exception e) {
        throw new BadRequestException("An error occured durin Concept Map Compare DSV export: %s", Throwables.getRootCause(e).getMessage());
    }
    return Paths.get(filePath).toFile();
}
Also used : OutputStream(java.io.OutputStream) BadRequestException(com.b2international.commons.exceptions.BadRequestException) Files(java.nio.file.Files) Request(com.b2international.snowowl.core.events.Request) CsvMapper(com.fasterxml.jackson.dataformat.csv.CsvMapper) StandardOpenOption(java.nio.file.StandardOpenOption) CsvSchema(com.fasterxml.jackson.dataformat.csv.CsvSchema) Set(java.util.Set) Throwables(com.google.common.base.Throwables) Collectors(java.util.stream.Collectors) File(java.io.File) List(java.util.List) Paths(java.nio.file.Paths) ConceptMapCompareChangeKind(com.b2international.snowowl.core.compare.ConceptMapCompareChangeKind) ServiceProvider(com.b2international.snowowl.core.ServiceProvider) ConceptMapCompareResultItem(com.b2international.snowowl.core.compare.ConceptMapCompareResultItem) CsvSchema(com.fasterxml.jackson.dataformat.csv.CsvSchema) CsvMapper(com.fasterxml.jackson.dataformat.csv.CsvMapper) OutputStream(java.io.OutputStream) BadRequestException(com.b2international.commons.exceptions.BadRequestException) ConceptMapCompareResultItem(com.b2international.snowowl.core.compare.ConceptMapCompareResultItem) BadRequestException(com.b2international.commons.exceptions.BadRequestException)

Example 27 with BadRequestException

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

the class EsDocumentSearcher method applySourceFiltering.

private <T> boolean applySourceFiltering(List<String> fields, final DocumentMapping mapping, final SearchSourceBuilder reqSource) {
    // No specific fields requested? Use _source to retrieve all of them
    if (fields.isEmpty()) {
        reqSource.fetchSource(true);
        return true;
    }
    // check if any fields requested are not supported by the mapping and fail-fast
    SortedSet<String> unrecognizedFields = getUnrecognizedFields(mapping, fields);
    if (!unrecognizedFields.isEmpty()) {
        throw new BadRequestException("Unrecognized %s model propert%s '%s'.", mapping.typeAsString(), unrecognizedFields.size() == 1 ? "y" : "ies", unrecognizedFields).withDeveloperMessage("Supported properties are '%s'.", mapping.getSelectableFields());
    }
    // Any field requested that can only retrieved from _source? Use source filtering
    if (requiresDocumentSourceField(mapping, fields)) {
        reqSource.fetchSource(Iterables.toArray(fields, String.class), null);
        return true;
    }
    // Use docValues otherwise for field retrieval
    fields.stream().forEach(field -> reqSource.docValueField(field));
    reqSource.fetchSource(false);
    return false;
}
Also used : BadRequestException(com.b2international.commons.exceptions.BadRequestException)

Example 28 with BadRequestException

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

the class DefaultResourceURIPathResolver method resolveWithVersion.

@Override
public PathWithVersion resolveWithVersion(ServiceProvider context, ResourceURI uriToResolve, Resource resource) {
    if (resource instanceof TerminologyResource) {
        TerminologyResource terminologyResource = (TerminologyResource) resource;
        if (uriToResolve.isHead()) {
            // use code system working branch directly when HEAD is specified
            final String workingBranchPath = terminologyResource.getBranchPath() + uriToResolve.getTimestampPart();
            return new PathWithVersion(workingBranchPath);
        }
        // prevent running version search if path does not look like a versionId (single path segment)
        final String relativeBranchPath = terminologyResource.getRelativeBranchPath(uriToResolve.getPath());
        if (uriToResolve.getPath().contains(Branch.SEPARATOR)) {
            final String absoluteBranchPath = relativeBranchPath + uriToResolve.getTimestampPart();
            return new PathWithVersion(absoluteBranchPath);
        }
        VersionSearchRequestBuilder versionSearch = ResourceRequests.prepareSearchVersion().one().filterByResource(terminologyResource.getResourceURI());
        if (uriToResolve.isLatest()) {
            // fetch the latest resource version if LATEST is specified in the URI
            versionSearch.sortBy(SearchResourceRequest.Sort.fieldDesc(VersionDocument.Fields.EFFECTIVE_TIME));
        } else {
            // try to fetch the path as exact version if not the special LATEST is specified in the URI
            versionSearch.filterByVersionId(uriToResolve.getPath());
        }
        // determine the final branch path, if based on the version search we find a version, then use that, otherwise use the defined path as relative branch of the code system working branch
        Versions versions = versionSearch.buildAsync().getRequest().execute(context);
        return versions.first().map(v -> {
            final String versionBranchPath = v.getBranchPath() + uriToResolve.getTimestampPart();
            final ResourceURI versionResourceURI = v.getVersionResourceURI().withTimestampPart(uriToResolve.getTimestampPart());
            return new PathWithVersion(versionBranchPath, versionResourceURI);
        }).orElseGet(() -> {
            if (uriToResolve.isLatest() || !allowBranches) {
                throw new BadRequestException("No Resource version is present in '%s'. Explicit '%s' can be used to retrieve the latest work in progress version of the Resource.", terminologyResource.getId(), terminologyResource.getId());
            }
            return new PathWithVersion(relativeBranchPath);
        });
    }
    return new PathWithVersion("");
}
Also used : VersionSearchRequestBuilder(com.b2international.snowowl.core.request.version.VersionSearchRequestBuilder) BadRequestException(com.b2international.commons.exceptions.BadRequestException) TerminologyResource(com.b2international.snowowl.core.TerminologyResource) ResourceRequests(com.b2international.snowowl.core.request.ResourceRequests) VersionSearchRequestBuilder(com.b2international.snowowl.core.request.version.VersionSearchRequestBuilder) Set(java.util.Set) Collectors(java.util.stream.Collectors) Branch(com.b2international.snowowl.core.branch.Branch) SearchResourceRequest(com.b2international.snowowl.core.request.SearchResourceRequest) Resource(com.b2international.snowowl.core.Resource) List(java.util.List) VersionDocument(com.b2international.snowowl.core.version.VersionDocument) Map(java.util.Map) ServiceProvider(com.b2international.snowowl.core.ServiceProvider) CompareUtils(com.b2international.commons.CompareUtils) Collections(java.util.Collections) Versions(com.b2international.snowowl.core.version.Versions) ResourceURI(com.b2international.snowowl.core.ResourceURI) ResourceURI(com.b2international.snowowl.core.ResourceURI) Versions(com.b2international.snowowl.core.version.Versions) TerminologyResource(com.b2international.snowowl.core.TerminologyResource) BadRequestException(com.b2international.commons.exceptions.BadRequestException)

Example 29 with BadRequestException

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

the class IdRequest method execute.

@Override
public R execute(final C context) {
    final IdActionRecorder recorder = new IdActionRecorder(context);
    try {
        final Multimap<ComponentCategory, SnomedComponentCreateRequest> componentCreateRequests = getComponentCreateRequests(next());
        if (!componentCreateRequests.isEmpty()) {
            try {
                for (final ComponentCategory category : componentCreateRequests.keySet()) {
                    final Class<? extends SnomedDocument> documentClass = getDocumentClass(category);
                    final Collection<SnomedComponentCreateRequest> categoryRequests = componentCreateRequests.get(category);
                    final Set<String> coreComponentIds = FluentIterable.from(categoryRequests).filter(SnomedCoreComponentCreateRequest.class).filter(request -> request.getIdGenerationStrategy() instanceof ConstantIdStrategy).transform(request -> ((ConstantIdStrategy) request.getIdGenerationStrategy()).getId()).toSet();
                    final Set<String> refsetMemberIds = FluentIterable.from(categoryRequests).filter(SnomedRefSetMemberCreateRequest.class).transform(request -> request.getId()).toSet();
                    final Set<String> userRequestedIds = Sets.newHashSet(Iterables.concat(coreComponentIds, refsetMemberIds));
                    final Set<String> existingIds = getExistingIds(context, userRequestedIds, documentClass);
                    if (!existingIds.isEmpty()) {
                        // TODO: Report all existing identifiers
                        throw new AlreadyExistsException(category.getDisplayName(), Iterables.getFirst(existingIds, null));
                    } else {
                        if (!coreComponentIds.isEmpty()) {
                            recorder.register(coreComponentIds);
                        }
                    }
                    final Multimap<String, BaseSnomedComponentCreateRequest> requestsByNamespace = HashMultimap.create();
                    // index requests where an explicit namespace identifier is specified (use it directly)
                    categoryRequests.stream().filter(BaseSnomedComponentCreateRequest.class::isInstance).map(BaseSnomedComponentCreateRequest.class::cast).filter(request -> request.getIdGenerationStrategy() instanceof NamespaceIdStrategy).forEach(request -> {
                        requestsByNamespace.put(getNamespaceKey(request), request);
                    });
                    // convert requests that define a namespaceConceptId by extracting the namespaceId from the namespaceConcept's FSN
                    final Multimap<String, BaseSnomedComponentCreateRequest> requestsByNamespaceConceptId = HashMultimap.create();
                    categoryRequests.stream().filter(BaseSnomedComponentCreateRequest.class::isInstance).map(BaseSnomedComponentCreateRequest.class::cast).filter(request -> request.getIdGenerationStrategy() instanceof NamespaceConceptIdStrategy).forEach(request -> {
                        requestsByNamespaceConceptId.put(request.getIdGenerationStrategy().getNamespace(), request);
                    });
                    if (!requestsByNamespaceConceptId.isEmpty()) {
                        final Map<String, String> namespacesByNamespaceConceptId = context.service(NamespaceIdProvider.class).extractNamespaceIds(context, requestsByNamespaceConceptId.keySet(), false);
                        for (String namespaceConceptId : Set.copyOf(requestsByNamespaceConceptId.keySet())) {
                            Collection<BaseSnomedComponentCreateRequest> requests = requestsByNamespaceConceptId.removeAll(namespaceConceptId);
                            if (!namespacesByNamespaceConceptId.containsKey(namespaceConceptId)) {
                                throw new BadRequestException("There is no namespace value associated with the '%s' namespaceConcept's FSN.", namespaceConceptId);
                            }
                            requestsByNamespace.putAll(namespacesByNamespaceConceptId.get(namespaceConceptId), requests);
                        }
                    }
                    for (final String namespace : requestsByNamespace.keySet()) {
                        final String convertedNamespace = SnomedIdentifiers.INT_NAMESPACE.equals(namespace) ? null : namespace;
                        final Collection<BaseSnomedComponentCreateRequest> namespaceRequests = requestsByNamespace.get(namespace);
                        final int count = namespaceRequests.size();
                        final Set<String> uniqueIds = getUniqueIds(context, recorder, category, documentClass, count, convertedNamespace);
                        final Iterator<String> idsToUse = Iterators.consumingIterator(uniqueIds.iterator());
                        for (final BaseSnomedComponentCreateRequest createRequest : namespaceRequests) {
                            createRequest.setIdGenerationStrategy(new ConstantIdStrategy(idsToUse.next()));
                        }
                        checkState(!idsToUse.hasNext(), "More SNOMED CT ids have been requested than used.");
                    }
                }
            } finally {
            // idGenerationSample.stop(registry.timer("idGenerationTime"));
            }
        }
        final R commitInfo = next(context);
        recorder.commit();
        return commitInfo;
    } catch (final Exception e) {
        recorder.rollback();
        throw e;
    }
}
Also used : Query(com.b2international.index.query.Query) AlreadyExistsException(com.b2international.commons.exceptions.AlreadyExistsException) RevisionSearcher(com.b2international.index.revision.RevisionSearcher) IdActionRecorder(com.b2international.snowowl.snomed.cis.action.IdActionRecorder) NamespaceIdStrategy(com.b2international.snowowl.snomed.core.domain.NamespaceIdStrategy) Map(java.util.Map) BulkRequest(com.b2international.snowowl.core.events.bulk.BulkRequest) com.b2international.snowowl.snomed.datastore.index.entry(com.b2international.snowowl.snomed.datastore.index.entry) Sets.newHashSet(com.google.common.collect.Sets.newHashSet) CompareUtils(com.b2international.commons.CompareUtils) com.google.common.collect(com.google.common.collect) BadRequestException(com.b2international.commons.exceptions.BadRequestException) Iterator(java.util.Iterator) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) RevisionDocument(com.b2international.snowowl.core.repository.RevisionDocument) Collection(java.util.Collection) Request(com.b2international.snowowl.core.events.Request) Set(java.util.Set) IOException(java.io.IOException) Preconditions.checkState(com.google.common.base.Preconditions.checkState) ConstantIdStrategy(com.b2international.snowowl.snomed.core.domain.ConstantIdStrategy) TransactionalRequest(com.b2international.snowowl.core.request.TransactionalRequest) IdGenerationStrategy(com.b2international.snowowl.snomed.core.domain.IdGenerationStrategy) DelegatingRequest(com.b2international.snowowl.core.events.DelegatingRequest) SnomedIdentifiers(com.b2international.snowowl.snomed.cis.SnomedIdentifiers) NamespaceConceptIdStrategy(com.b2international.snowowl.snomed.core.domain.NamespaceConceptIdStrategy) BranchContext(com.b2international.snowowl.core.domain.BranchContext) NotImplementedException(com.b2international.commons.exceptions.NotImplementedException) ComponentCategory(com.b2international.snowowl.core.terminology.ComponentCategory) IdActionRecorder(com.b2international.snowowl.snomed.cis.action.IdActionRecorder) AlreadyExistsException(com.b2international.commons.exceptions.AlreadyExistsException) ComponentCategory(com.b2international.snowowl.core.terminology.ComponentCategory) AlreadyExistsException(com.b2international.commons.exceptions.AlreadyExistsException) BadRequestException(com.b2international.commons.exceptions.BadRequestException) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) IOException(java.io.IOException) NotImplementedException(com.b2international.commons.exceptions.NotImplementedException) ConstantIdStrategy(com.b2international.snowowl.snomed.core.domain.ConstantIdStrategy) BadRequestException(com.b2international.commons.exceptions.BadRequestException) NamespaceIdStrategy(com.b2international.snowowl.snomed.core.domain.NamespaceIdStrategy) NamespaceConceptIdStrategy(com.b2international.snowowl.snomed.core.domain.NamespaceConceptIdStrategy)

Example 30 with BadRequestException

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

the class SaveJobRequest method persistChanges.

private Boolean persistChanges(final BranchContext context, final IProgressMonitor monitor) {
    // Repeat the same checks as in ClassificationSaveRequest, now within the lock
    final ClassificationTask classification = ClassificationRequests.prepareGetClassification(classificationId).build().execute(context);
    final String branchPath = classification.getBranch();
    final Branch branch = RepositoryRequests.branching().prepareGet(branchPath).build().execute(context);
    if (!ClassificationSaveRequest.SAVEABLE_STATUSES.contains(classification.getStatus())) {
        throw new BadRequestException("Classification '%s' is not in the expected state to start saving changes.", classificationId);
    }
    if (classification.getTimestamp() < branch.headTimestamp()) {
        throw new BadRequestException("Classification '%s' on branch '%s' is stale (classification timestamp: %s, head timestamp: %s).", classificationId, branchPath, classification.getTimestamp(), branch.headTimestamp());
    }
    final ClassificationTracker classificationTracker = context.service(ClassificationTracker.class);
    // Signal the state change
    classificationTracker.classificationSaving(classificationId);
    final SubMonitor subMonitor = SubMonitor.convert(monitor, "Persisting changes", 6);
    final BulkRequestBuilder<TransactionContext> bulkRequestBuilder = BulkRequest.create();
    applyChanges(subMonitor, context, bulkRequestBuilder);
    long resultTimeStamp = Commit.NO_COMMIT_TIMESTAMP;
    for (List<Request<TransactionContext, ?>> partition : Iterables.partition(bulkRequestBuilder.build().getRequests(), getCommitLimit(context))) {
        final BulkRequestBuilder<TransactionContext> batchRequest = BulkRequest.create();
        partition.forEach(request -> batchRequest.add(request));
        final Request<BranchContext, CommitResult> commitRequest = SnomedRequests.prepareCommit().setBody(batchRequest.build()).setCommitComment(commitComment).setParentContextDescription(DatastoreLockContextDescriptions.SAVE_CLASSIFICATION_RESULTS).setAuthor(userId).build();
        final CommitResult commitResult = new IdRequest<>(commitRequest).execute(context);
        resultTimeStamp = commitResult.getCommitTimestamp();
    }
    if (Commit.NO_COMMIT_TIMESTAMP == resultTimeStamp) {
        classificationTracker.classificationSaveFailed(classificationId);
        return Boolean.FALSE;
    } else {
        classificationTracker.classificationSaved(classificationId, resultTimeStamp);
        return Boolean.TRUE;
    }
}
Also used : CommitResult(com.b2international.snowowl.core.request.CommitResult) SubMonitor(org.eclipse.core.runtime.SubMonitor) Request(com.b2international.snowowl.core.events.Request) BulkRequest(com.b2international.snowowl.core.events.bulk.BulkRequest) Branch(com.b2international.snowowl.core.branch.Branch) TransactionContext(com.b2international.snowowl.core.domain.TransactionContext) BranchContext(com.b2international.snowowl.core.domain.BranchContext) BadRequestException(com.b2international.commons.exceptions.BadRequestException) ClassificationTracker(com.b2international.snowowl.snomed.reasoner.classification.ClassificationTracker)

Aggregations

BadRequestException (com.b2international.commons.exceptions.BadRequestException)41 IOException (java.io.IOException)8 Collectors (java.util.stream.Collectors)7 ResourceURI (com.b2international.snowowl.core.ResourceURI)6 BranchContext (com.b2international.snowowl.core.domain.BranchContext)6 Request (com.b2international.snowowl.core.events.Request)6 List (java.util.List)6 Map (java.util.Map)6 Options (com.b2international.commons.options.Options)5 Branch (com.b2international.snowowl.core.branch.Branch)5 Set (java.util.Set)5 CompareUtils (com.b2international.commons.CompareUtils)4 ExpressionBuilder (com.b2international.index.query.Expressions.ExpressionBuilder)4 SnowowlRuntimeException (com.b2international.snowowl.core.api.SnowowlRuntimeException)4 SnomedRefSetType (com.b2international.snowowl.snomed.core.domain.refset.SnomedRefSetType)4 Collection (java.util.Collection)4 AlreadyExistsException (com.b2international.commons.exceptions.AlreadyExistsException)3 ConflictException (com.b2international.commons.exceptions.ConflictException)3 NotFoundException (com.b2international.commons.exceptions.NotFoundException)3 ExtendedLocale (com.b2international.commons.http.ExtendedLocale)3