Search in sources :

Example 1 with TrellisRuntimeException

use of org.trellisldp.api.TrellisRuntimeException in project trellis by trellis-ldp.

the class DBResourceService method storeResource.

private void storeResource(final Metadata metadata, final Dataset dataset, final Instant time, final OperationType opType) {
    try {
        jdbi.useTransaction(handle -> {
            final int resourceId = updateResource(handle, metadata, dataset, time, opType == OperationType.DELETE);
            updateDescription(handle, resourceId, dataset, batchSize);
            updateAcl(handle, resourceId, dataset, batchSize);
            updateExtra(handle, resourceId, metadata.getIdentifier(), dataset);
            extensions.forEach((ext, graph) -> dataset.getGraph(graph).filter(g -> !"acl".equals(ext)).ifPresent(g -> updateExtension(handle, resourceId, ext, g)));
            if (opType == OperationType.DELETE) {
                // Verify that the container really is empty
                final String query = "SELECT EXISTS(SELECT 1 FROM resource WHERE is_part_of = ?)";
                if (Boolean.TRUE.equals(handle.select(query, metadata.getIdentifier().getIRIString()).map((rs, ctx) -> rs.getBoolean(1)).one())) {
                    throw new StorageConflictException("Cannot delete non-empty containers");
                }
            }
        });
    } catch (final TrellisRuntimeException ex) {
        throw ex;
    } catch (final Exception ex) {
        throw new TrellisRuntimeException("Could not update data for " + metadata.getIdentifier(), ex);
    }
}
Also used : IdentifierService(org.trellisldp.api.IdentifierService) TrellisRuntimeException(org.trellisldp.api.TrellisRuntimeException) PreparedBatch(org.jdbi.v3.core.statement.PreparedBatch) Optional.of(java.util.Optional.of) NTRIPLES(org.apache.jena.riot.Lang.NTRIPLES) Resource(org.trellisldp.api.Resource) PreferAudit(org.trellisldp.vocabulary.Trellis.PreferAudit) Collectors.toMap(java.util.stream.Collectors.toMap) Arrays.asList(java.util.Arrays.asList) JenaCommonsRDF.toJena(org.apache.jena.commonsrdf.JenaCommonsRDF.toJena) Map(java.util.Map) Handle(org.jdbi.v3.core.Handle) Graph(org.apache.commons.rdf.api.Graph) Set(java.util.Set) Instant(java.time.Instant) UncheckedIOException(java.io.UncheckedIOException) CompletionStage(java.util.concurrent.CompletionStage) StorageConflictException(org.trellisldp.api.StorageConflictException) PostConstruct(javax.annotation.PostConstruct) Optional(java.util.Optional) ApplicationScoped(javax.enterprise.context.ApplicationScoped) Arrays.stream(java.util.Arrays.stream) Instant.now(java.time.Instant.now) DBUtils.getObjectLang(org.trellisldp.jdbc.DBUtils.getObjectLang) PreferAccessControl(org.trellisldp.vocabulary.Trellis.PreferAccessControl) Supplier(java.util.function.Supplier) RDF(org.apache.commons.rdf.api.RDF) Triple(org.apache.commons.rdf.api.Triple) HashSet(java.util.HashSet) Inject(javax.inject.Inject) Metadata(org.trellisldp.api.Metadata) ResourceService(org.trellisldp.api.ResourceService) DBUtils.getObjectDatatype(org.trellisldp.jdbc.DBUtils.getObjectDatatype) DataSource(javax.sql.DataSource) Collections.singletonMap(java.util.Collections.singletonMap) LDP(org.trellisldp.vocabulary.LDP) Dataset(org.apache.commons.rdf.api.Dataset) DBUtils.getObjectValue(org.trellisldp.jdbc.DBUtils.getObjectValue) Jdbi(org.jdbi.v3.core.Jdbi) BinaryMetadata(org.trellisldp.api.BinaryMetadata) RDFFactory(org.trellisldp.api.RDFFactory) CompletableFuture.runAsync(java.util.concurrent.CompletableFuture.runAsync) Logger(org.slf4j.Logger) StringWriter(java.io.StringWriter) IOException(java.io.IOException) TrellisUtils(org.trellisldp.api.TrellisUtils) IRI(org.apache.commons.rdf.api.IRI) OA(org.trellisldp.vocabulary.OA) Collections.unmodifiableSet(java.util.Collections.unmodifiableSet) RDFDataMgr(org.apache.jena.riot.RDFDataMgr) LoggerFactory.getLogger(org.slf4j.LoggerFactory.getLogger) Update(org.jdbi.v3.core.statement.Update) ConfigProperty(org.eclipse.microprofile.config.inject.ConfigProperty) PreferUserManaged(org.trellisldp.vocabulary.Trellis.PreferUserManaged) TrellisRuntimeException(org.trellisldp.api.TrellisRuntimeException) StorageConflictException(org.trellisldp.api.StorageConflictException) TrellisRuntimeException(org.trellisldp.api.TrellisRuntimeException) UncheckedIOException(java.io.UncheckedIOException) StorageConflictException(org.trellisldp.api.StorageConflictException) IOException(java.io.IOException)

Example 2 with TrellisRuntimeException

use of org.trellisldp.api.TrellisRuntimeException in project trellis by trellis-ldp.

the class TriplestoreResourceService method delete.

@Override
public CompletionStage<Void> delete(final Metadata metadata) {
    LOGGER.debug("Deleting: {}", metadata.getIdentifier());
    return runAsync(() -> {
        try (final Dataset dataset = rdf.createDataset()) {
            final Instant eventTime = now();
            dataset.add(PreferServerManaged, metadata.getIdentifier(), DC.type, DeletedResource);
            dataset.add(PreferServerManaged, metadata.getIdentifier(), type, LDP.Resource);
            storeResource(metadata.getIdentifier(), dataset, eventTime, OperationType.DELETE);
        } catch (final Exception ex) {
            throw new TrellisRuntimeException("Error deleting resource: " + metadata.getIdentifier(), ex);
        }
    });
}
Also used : TrellisRuntimeException(org.trellisldp.api.TrellisRuntimeException) Dataset(org.apache.commons.rdf.api.Dataset) Instant(java.time.Instant) TrellisRuntimeException(org.trellisldp.api.TrellisRuntimeException)

Example 3 with TrellisRuntimeException

use of org.trellisldp.api.TrellisRuntimeException in project trellis by trellis-ldp.

the class PatchHandler method assembleResponse.

private CompletionStage<ResponseBuilder> assembleResponse(final Dataset mutable, final Dataset immutable, final ResponseBuilder builder) {
    final IRI ext = getExtensionGraphName();
    final IRI graphName = ext != null ? ext : PreferUserManaged;
    // Put triples in buffer, short-circuit on exception
    final List<Triple> triples;
    try {
        triples = updateGraph(syntax, graphName);
    } catch (final TrellisRuntimeException ex) {
        throw new BadRequestException("Invalid RDF: " + ex.getMessage(), ex);
    }
    triples.stream().map(skolemizeTriples(getServices().getResourceService(), getBaseUrl())).map(triple -> rdf.createQuad(graphName, triple.getSubject(), triple.getPredicate(), triple.getObject())).forEachOrdered(mutable::add);
    // Check any constraints on the resulting dataset
    final List<ConstraintViolation> violations = new ArrayList<>();
    getServices().getConstraintServices().forEach(svc -> handleConstraintViolation(svc, getInternalId(), mutable, graphName, getLdpType()).forEach(violations::add));
    // Short-ciruit if there is a constraint violation
    if (!violations.isEmpty()) {
        final ResponseBuilder err = status(CONFLICT);
        violations.forEach(v -> err.link(v.getConstraint().getIRIString(), LDP.constrainedBy.getIRIString()));
        throw new ClientErrorException(err.entity((StreamingOutput) out -> getServices().getIOService().write(violations.stream().flatMap(v2 -> v2.getTriples().stream()), out, RDFSyntax.TURTLE, getIdentifier())).type(RDFSyntax.TURTLE.mediaType()).build());
    }
    // When updating one particular graph, be sure to add the other category to the dataset
    if (getResource() != null) {
        try (final Stream<Quad> remaining = getResource().stream(getNonCurrentGraphNames())) {
            remaining.forEachOrdered(mutable::add);
        }
    }
    // Collect the audit data
    getAuditQuadData().forEachOrdered(immutable::add);
    final Metadata metadata;
    if (getResource() == null) {
        metadata = metadataBuilder(getInternalId(), LDP.RDFSource, mutable).container(TrellisUtils.getContainer(getInternalId()).orElse(null)).build();
    } else {
        final Metadata.Builder mbuilder = metadataBuilder(getResource().getIdentifier(), getResource().getInteractionModel(), mutable);
        getResource().getContainer().ifPresent(mbuilder::container);
        getResource().getBinaryMetadata().ifPresent(mbuilder::binary);
        mbuilder.revision(getResource().getRevision());
        metadata = mbuilder.build();
    }
    return createOrReplace(metadata, mutable, immutable).thenCompose(future -> emitNotification(metadata.getIdentifier(), getResource() == null ? AS.Create : AS.Update, getLdpType(), metadata.getRevision().orElse(null))).thenApply(future -> {
        final RDFSyntax outputSyntax = getSyntax(getServices().getIOService(), getRequest().getAcceptableMediaTypes(), null);
        if (preference != null) {
            final IRI profile = getResponseProfile(outputSyntax);
            return builder.header(PREFERENCE_APPLIED, "return=representation").type(outputSyntax.mediaType()).entity((StreamingOutput) out -> getServices().getIOService().write(triples.stream().map(unskolemizeTriples(getServices().getResourceService(), getBaseUrl())), out, outputSyntax, getIdentifier(), profile));
        }
        return builder.status(getResource() == null ? CREATED : NO_CONTENT);
    });
}
Also used : HttpUtils.getProfile(org.trellisldp.http.impl.HttpUtils.getProfile) TrellisRuntimeException(org.trellisldp.api.TrellisRuntimeException) HttpUtils.getDefaultProfile(org.trellisldp.http.impl.HttpUtils.getDefaultProfile) ConstraintService(org.trellisldp.api.ConstraintService) HttpUtils.unskolemizeTriples(org.trellisldp.http.impl.HttpUtils.unskolemizeTriples) HttpUtils.ldpResourceTypes(org.trellisldp.http.impl.HttpUtils.ldpResourceTypes) NotAllowedException(javax.ws.rs.NotAllowedException) Prefer(org.trellisldp.common.Prefer) ClientErrorException(javax.ws.rs.ClientErrorException) Resource(org.trellisldp.api.Resource) HttpUtils.getSyntax(org.trellisldp.http.impl.HttpUtils.getSyntax) MediaType(javax.ws.rs.core.MediaType) Map(java.util.Map) Graph(org.apache.commons.rdf.api.Graph) Response.status(javax.ws.rs.core.Response.status) BadRequestException(javax.ws.rs.BadRequestException) HttpUtils.exists(org.trellisldp.http.impl.HttpUtils.exists) DELETED_RESOURCE(org.trellisldp.api.Resource.SpecialResources.DELETED_RESOURCE) BAD_REQUEST(javax.ws.rs.core.Response.Status.BAD_REQUEST) CONFLICT(javax.ws.rs.core.Response.Status.CONFLICT) StreamingOutput(javax.ws.rs.core.StreamingOutput) NotFoundException(javax.ws.rs.NotFoundException) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) Stream(java.util.stream.Stream) Response.ok(javax.ws.rs.core.Response.ok) CREATED(javax.ws.rs.core.Response.Status.CREATED) Link(javax.ws.rs.core.Link) ServiceBundler(org.trellisldp.common.ServiceBundler) HttpMethod(javax.ws.rs.HttpMethod) HttpUtils.skolemizeTriples(org.trellisldp.http.impl.HttpUtils.skolemizeTriples) ArrayList(java.util.ArrayList) Triple(org.apache.commons.rdf.api.Triple) PREFERENCE_APPLIED(org.trellisldp.common.HttpConstants.PREFERENCE_APPLIED) ConstraintViolation(org.trellisldp.api.ConstraintViolation) RDF(org.trellisldp.vocabulary.RDF) AS(org.trellisldp.vocabulary.AS) Metadata(org.trellisldp.api.Metadata) GONE(javax.ws.rs.core.Response.Status.GONE) UnsupportedInteractionModel(org.trellisldp.vocabulary.Trellis.UnsupportedInteractionModel) LDP(org.trellisldp.vocabulary.LDP) Dataset(org.apache.commons.rdf.api.Dataset) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) NotSupportedException(javax.ws.rs.NotSupportedException) PREFER_REPRESENTATION(org.trellisldp.common.Prefer.PREFER_REPRESENTATION) TrellisRequest(org.trellisldp.common.TrellisRequest) Logger(org.slf4j.Logger) NO_CONTENT(javax.ws.rs.core.Response.Status.NO_CONTENT) TrellisUtils(org.trellisldp.api.TrellisUtils) HttpUtils.closeDataset(org.trellisldp.http.impl.HttpUtils.closeDataset) TEXT_PLAIN_TYPE(javax.ws.rs.core.MediaType.TEXT_PLAIN_TYPE) Collectors.toList(java.util.stream.Collectors.toList) IRI(org.apache.commons.rdf.api.IRI) Quad(org.apache.commons.rdf.api.Quad) RDFSyntax(org.apache.commons.rdf.api.RDFSyntax) LoggerFactory.getLogger(org.slf4j.LoggerFactory.getLogger) MISSING_RESOURCE(org.trellisldp.api.Resource.SpecialResources.MISSING_RESOURCE) PreferUserManaged(org.trellisldp.vocabulary.Trellis.PreferUserManaged) IRI(org.apache.commons.rdf.api.IRI) Quad(org.apache.commons.rdf.api.Quad) ArrayList(java.util.ArrayList) Metadata(org.trellisldp.api.Metadata) StreamingOutput(javax.ws.rs.core.StreamingOutput) Triple(org.apache.commons.rdf.api.Triple) TrellisRuntimeException(org.trellisldp.api.TrellisRuntimeException) ConstraintViolation(org.trellisldp.api.ConstraintViolation) BadRequestException(javax.ws.rs.BadRequestException) ClientErrorException(javax.ws.rs.ClientErrorException) RDFSyntax(org.apache.commons.rdf.api.RDFSyntax) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder)

Example 4 with TrellisRuntimeException

use of org.trellisldp.api.TrellisRuntimeException in project trellis by trellis-ldp.

the class AbstractTrellisHttpResourceTest method testPostException.

@Test
void testPostException() {
    when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
    when(mockResourceService.get(identifier)).thenAnswer(inv -> supplyAsync(() -> {
        throw new TrellisRuntimeException(EXPECTED_EXCEPTION);
    }));
    try (final Response res = target(RESOURCE_PATH).request().post(entity("", TEXT_TURTLE_TYPE))) {
        assertEquals(SC_INTERNAL_SERVER_ERROR, res.getStatus(), ERR_RESPONSE_CODE);
    }
}
Also used : Response(javax.ws.rs.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) TrellisRuntimeException(org.trellisldp.api.TrellisRuntimeException) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 5 with TrellisRuntimeException

use of org.trellisldp.api.TrellisRuntimeException in project trellis by trellis-ldp.

the class TrellisHttpResourceTest method testInitializeExistingLdpResourceWithFailure.

@Test
void testInitializeExistingLdpResourceWithFailure() throws Exception {
    final ResourceService mockService = mock(ResourceService.class);
    when(mockBundler.getResourceService()).thenReturn(mockService);
    when(mockService.get(root)).thenAnswer(inv -> runAsync(() -> {
        throw new TrellisRuntimeException("Expected exception");
    }));
    final TrellisHttpResource matcher = new TrellisHttpResource();
    matcher.services = mockBundler;
    assertDoesNotThrow(() -> matcher.initialize());
    assertAll("Verify interactions with init-errored resource service", verifyInteractions(mockService));
}
Also used : TrellisRuntimeException(org.trellisldp.api.TrellisRuntimeException) ResourceService(org.trellisldp.api.ResourceService) Test(org.junit.jupiter.api.Test)

Aggregations

TrellisRuntimeException (org.trellisldp.api.TrellisRuntimeException)18 Dataset (org.apache.commons.rdf.api.Dataset)9 IRI (org.apache.commons.rdf.api.IRI)9 CompletionStage (java.util.concurrent.CompletionStage)7 Logger (org.slf4j.Logger)7 LoggerFactory.getLogger (org.slf4j.LoggerFactory.getLogger)7 Metadata (org.trellisldp.api.Metadata)7 Resource (org.trellisldp.api.Resource)7 PostConstruct (javax.annotation.PostConstruct)6 Inject (javax.inject.Inject)6 RDF (org.apache.commons.rdf.api.RDF)6 Triple (org.apache.commons.rdf.api.Triple)6 RDFFactory (org.trellisldp.api.RDFFactory)6 ResourceService (org.trellisldp.api.ResourceService)6 Map (java.util.Map)5 Optional (java.util.Optional)5 Set (java.util.Set)5 Stream (java.util.stream.Stream)5 ApplicationScoped (javax.enterprise.context.ApplicationScoped)5 Graph (org.apache.commons.rdf.api.Graph)5