use of com.b2international.commons.exceptions.AlreadyExistsException in project snow-owl by b2ihealthcare.
the class BaseResourceCreateRequest method execute.
@Override
public final String execute(TransactionContext context) {
// validate ID before use, IDs sometimes being used as branch paths, so must be a valid branch path
try {
BranchNameValidator.DEFAULT.checkName(id);
} catch (BadRequestException e) {
throw new BadRequestException(e.getMessage().replace("Branch name", getClass().getSimpleName().replace("CreateRequest", ".id")));
}
// validate URL format
getResourceURLSchemaSupport(context).validate(url);
// id checked against all resources
final boolean existingId = ResourceRequests.prepareSearch().setLimit(0).filterById(getId()).build().execute(context).getTotal() > 0;
if (existingId) {
throw new AlreadyExistsException("Resource", getId());
}
// url checked against all resources
final boolean existingUrl = ResourceRequests.prepareSearch().setLimit(0).filterByUrl(getUrl()).build().execute(context).getTotal() > 0;
if (existingUrl) {
throw new AlreadyExistsException("Resource", ResourceDocument.Fields.URL, getUrl());
}
preExecute(context);
final List<String> bundleAncestorIds;
if (IComponent.ROOT_ID.equals(bundleId)) {
// "-1" is the only key that will show up both as the parent and as an ancestor
bundleAncestorIds = List.of(IComponent.ROOT_ID);
} else {
final Bundles bundles = ResourceRequests.bundles().prepareSearch().filterById(bundleId).one().build().execute(context);
if (bundles.getTotal() == 0) {
throw new NotFoundException("Bundle parent", bundleId).toBadRequestException();
}
final Bundle bundleParent = bundles.first().get();
bundleAncestorIds = bundleParent.getResourcePathSegments();
}
context.add(createResourceDocument(context, bundleAncestorIds));
return id;
}
use of com.b2international.commons.exceptions.AlreadyExistsException in project snow-owl by b2ihealthcare.
the class BaseResourceUpdateRequest method execute.
@Override
public final Boolean execute(TransactionContext context) {
if (resource == null) {
resource = context.lookup(componentId(), ResourceDocument.class);
}
final ResourceDocument.Builder updated = ResourceDocument.builder(resource);
boolean changed = false;
changed |= updateSpecializedProperties(context, resource, updated);
// url checked against all resources
if (url != null && !url.equals(resource.getUrl())) {
if (url.isBlank()) {
throw new BadRequestException("Resource.url should not be empty string");
}
final boolean existingUrl = ResourceRequests.prepareSearch().setLimit(0).filterByUrl(url).build().execute(context).getTotal() > 0;
if (existingUrl) {
throw new AlreadyExistsException("Resource", ResourceDocument.Fields.URL, url);
}
changed |= updateProperty(url, resource::getUrl, updated::url);
}
changed |= updateBundle(context, resource.getId(), resource.getBundleId(), updated);
changed |= updateProperty(title, resource::getTitle, updated::title);
changed |= updateProperty(language, resource::getLanguage, updated::language);
changed |= updateProperty(description, resource::getDescription, updated::description);
changed |= updateProperty(status, resource::getStatus, updated::status);
changed |= updateProperty(copyright, resource::getCopyright, updated::copyright);
changed |= updateProperty(owner, resource::getOwner, updated::owner);
changed |= updateProperty(contact, resource::getContact, updated::contact);
changed |= updateProperty(usage, resource::getUsage, updated::usage);
changed |= updateProperty(purpose, resource::getPurpose, updated::purpose);
if (changed) {
// make sure we null out the updatedAt property we before update
updated.updatedAt(null);
context.update(resource, updated.build());
}
return changed;
}
use of com.b2international.commons.exceptions.AlreadyExistsException in project snow-owl by b2ihealthcare.
the class DefaultAttachmentRegistry method upload.
@Override
public void upload(UUID id, InputStream in) throws AlreadyExistsException, BadRequestException {
final File file = toFile(id);
if (file.exists()) {
throw new AlreadyExistsException("Zip File", id.toString());
}
final BufferedInputStream bin = new BufferedInputStream(in);
try {
new ByteSource() {
@Override
public InputStream openStream() throws IOException {
return bin;
}
}.copyTo(Files.asByteSink(file));
} catch (IOException e) {
throw new SnowowlRuntimeException("Failed to upload attachment of " + id, e);
}
}
use of com.b2international.commons.exceptions.AlreadyExistsException in project snow-owl by b2ihealthcare.
the class SnomedBranchRequestTest method createTwoBranchesSameTimeWithSameName.
@Test
public void createTwoBranchesSameTimeWithSameName() throws Exception {
final Branching branches = RepositoryRequests.branching();
// try to create two branches at the same time
final String branchName = UUID.randomUUID().toString();
final Promise<String> first = branches.prepareCreate().setParent(branchPath).setName(branchName).build(REPOSITORY_ID).execute(bus);
final Promise<String> second = branches.prepareCreate().setParent(branchPath).setName(branchName).build(REPOSITORY_ID).execute(bus);
final boolean sameBaseTimestamp = Promise.all(first, second).then(input -> {
final Branch first1 = branches.prepareGet((String) input.get(0)).build(REPOSITORY_ID).execute(bus).getSync();
final Branch second1 = branches.prepareGet((String) input.get(1)).build(REPOSITORY_ID).execute(bus).getSync();
return first1.baseTimestamp() == second1.baseTimestamp();
}).fail(e -> {
if (e instanceof AlreadyExistsException) {
return true;
} else {
throw new RuntimeException(e);
}
}).getSync();
// fail the test only when the API managed to create two branches with different base timestamp which should not happen
if (!sameBaseTimestamp) {
fail("Two branches created with the same name but different baseTimestamp");
}
}
use of com.b2international.commons.exceptions.AlreadyExistsException 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;
}
}
Aggregations