Search in sources :

Example 1 with AlreadyExistsException

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;
}
Also used : AlreadyExistsException(com.b2international.commons.exceptions.AlreadyExistsException) Bundle(com.b2international.snowowl.core.bundle.Bundle) BadRequestException(com.b2international.commons.exceptions.BadRequestException) NotFoundException(com.b2international.commons.exceptions.NotFoundException) Bundles(com.b2international.snowowl.core.bundle.Bundles)

Example 2 with AlreadyExistsException

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;
}
Also used : Builder(com.b2international.snowowl.core.internal.ResourceDocument.Builder) AlreadyExistsException(com.b2international.commons.exceptions.AlreadyExistsException) ResourceDocument(com.b2international.snowowl.core.internal.ResourceDocument) BadRequestException(com.b2international.commons.exceptions.BadRequestException)

Example 3 with AlreadyExistsException

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);
    }
}
Also used : AlreadyExistsException(com.b2international.commons.exceptions.AlreadyExistsException) BufferedInputStream(java.io.BufferedInputStream) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) ByteSource(com.google.common.io.ByteSource) IOException(java.io.IOException) File(java.io.File) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException)

Example 4 with AlreadyExistsException

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");
    }
}
Also used : BaseRevisionBranching(com.b2international.index.revision.BaseRevisionBranching) Branching(com.b2international.snowowl.core.branch.Branching) BaseRevisionBranching(com.b2international.index.revision.BaseRevisionBranching) Acceptability(com.b2international.snowowl.snomed.core.domain.Acceptability) SortedSet(java.util.SortedSet) RestExtensions(com.b2international.snowowl.test.commons.rest.RestExtensions) RevisionBranch(com.b2international.index.revision.RevisionBranch) Promise(com.b2international.snowowl.core.events.util.Promise) Branch(com.b2international.snowowl.core.branch.Branch) Merging(com.b2international.snowowl.core.branch.Merging) RepositoryRequests(com.b2international.snowowl.core.repository.RepositoryRequests) Concepts(com.b2international.snowowl.snomed.common.SnomedConstants.Concepts) SnomedRequests(com.b2international.snowowl.snomed.datastore.request.SnomedRequests) AlreadyExistsException(com.b2international.commons.exceptions.AlreadyExistsException) Assert.fail(org.junit.Assert.fail) SnomedDescriptionCreateRequestBuilder(com.b2international.snowowl.snomed.datastore.request.SnomedDescriptionCreateRequestBuilder) Branching(com.b2international.snowowl.core.branch.Branching) TestMethodNameRule(com.b2international.snowowl.test.commons.TestMethodNameRule) Before(org.junit.Before) BranchPathUtils(com.b2international.snowowl.core.branch.BranchPathUtils) CommitResult(com.b2international.snowowl.core.request.CommitResult) RepositoryManager(com.b2international.snowowl.core.RepositoryManager) ImmutableMap(com.google.common.collect.ImmutableMap) Request(com.b2international.snowowl.core.events.Request) Merge(com.b2international.snowowl.core.merge.Merge) JsonSupport(com.b2international.snowowl.core.repository.JsonSupport) Test(org.junit.Test) RevisionSegment(com.b2international.index.revision.RevisionSegment) RemoteJobEntry(com.b2international.snowowl.core.jobs.RemoteJobEntry) IEventBus(com.b2international.snowowl.eventbus.IEventBus) UUID(java.util.UUID) SnomedTerminologyComponentConstants(com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) Services(com.b2international.snowowl.test.commons.Services) Rule(org.junit.Rule) JobRequests(com.b2international.snowowl.core.jobs.JobRequests) ServiceProvider(com.b2international.snowowl.core.ServiceProvider) AsyncRequest(com.b2international.snowowl.core.events.AsyncRequest) User(com.b2international.snowowl.core.identity.User) SnomedIdentifiers(com.b2international.snowowl.snomed.cis.SnomedIdentifiers) Assert.assertEquals(org.junit.Assert.assertEquals) ApplicationContext(com.b2international.snowowl.core.ApplicationContext) AlreadyExistsException(com.b2international.commons.exceptions.AlreadyExistsException) RevisionBranch(com.b2international.index.revision.RevisionBranch) Branch(com.b2international.snowowl.core.branch.Branch) Test(org.junit.Test)

Example 5 with AlreadyExistsException

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;
    }
}
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)

Aggregations

AlreadyExistsException (com.b2international.commons.exceptions.AlreadyExistsException)6 BadRequestException (com.b2international.commons.exceptions.BadRequestException)3 SnowowlRuntimeException (com.b2international.snowowl.core.api.SnowowlRuntimeException)2 Request (com.b2international.snowowl.core.events.Request)2 SnomedIdentifiers (com.b2international.snowowl.snomed.cis.SnomedIdentifiers)2 CompareUtils (com.b2international.commons.CompareUtils)1 NotFoundException (com.b2international.commons.exceptions.NotFoundException)1 NotImplementedException (com.b2international.commons.exceptions.NotImplementedException)1 Query (com.b2international.index.query.Query)1 BaseRevisionBranching (com.b2international.index.revision.BaseRevisionBranching)1 RevisionBranch (com.b2international.index.revision.RevisionBranch)1 RevisionSearcher (com.b2international.index.revision.RevisionSearcher)1 RevisionSegment (com.b2international.index.revision.RevisionSegment)1 ApplicationContext (com.b2international.snowowl.core.ApplicationContext)1 RepositoryManager (com.b2international.snowowl.core.RepositoryManager)1 ServiceProvider (com.b2international.snowowl.core.ServiceProvider)1 Branch (com.b2international.snowowl.core.branch.Branch)1 BranchPathUtils (com.b2international.snowowl.core.branch.BranchPathUtils)1 Branching (com.b2international.snowowl.core.branch.Branching)1 Merging (com.b2international.snowowl.core.branch.Merging)1