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