Search in sources :

Example 1 with PreferUserManaged

use of org.trellisldp.vocabulary.Trellis.PreferUserManaged in project trellis by trellis-ldp.

the class TriplestoreResourceService method buildUpdateRequest.

/**
 * This is equivalent to the SPARQL below.
 *
 * <p><pre><code>
 * DELETE WHERE { GRAPH IDENTIFIER { ?s ?p ?o } };
 * DELETE WHERE { GRAPH IDENTIFIER?ext=acl { ?s ?p ?o } };
 * DELETE WHERE { GRAPH trellis:PreferServerManaged {
 *   IDENTIFIER a ldp:NonRDFSource .
 *   IDENTIFIER dc:hasPart ?s .
 *   ?s ?p ?o .
 * };
 * DELETE WHERE { GRAPH trellis:PreferServerManaged { IDENTIFIER ?p ?o } };
 * INSERT DATA {
 *   GRAPH IDENTIFIER { ... }
 *   GRAPH IDENTIFIER?ext=acl { ... }
 *   GRAPH trellis:PreferServerManaged { ... }
 *   GRAPH IDENTIFIER?ext=audit { ... }
 * }
 * </code></pre></p>
 */
private UpdateRequest buildUpdateRequest(final IRI identifier, final Literal time, final Dataset dataset, final OperationType operation) {
    // Set the time
    dataset.add(PreferServerManaged, identifier, DC.modified, time);
    final UpdateRequest req = new UpdateRequest();
    req.add(new UpdateDeleteWhere(new QuadAcc(singletonList(new Quad(toJena(identifier), SUBJECT, PREDICATE, OBJECT)))));
    extensions.forEach((ext, graph) -> req.add(new UpdateDeleteWhere(new QuadAcc(singletonList(new Quad(getExtIRI(identifier, ext), SUBJECT, PREDICATE, OBJECT))))));
    req.add(new UpdateDeleteWhere(new QuadAcc(asList(new Quad(toJena(PreferServerManaged), toJena(identifier), toJena(type), toJena(LDP.NonRDFSource)), new Quad(toJena(PreferServerManaged), toJena(identifier), toJena(DC.hasPart), SUBJECT), new Quad(toJena(PreferServerManaged), SUBJECT, PREDICATE, OBJECT)))));
    req.add(new UpdateDeleteWhere(new QuadAcc(singletonList(new Quad(toJena(PreferServerManaged), toJena(identifier), PREDICATE, OBJECT)))));
    final QuadDataAcc sink = new QuadDataAcc(synchronizedList(new ArrayList<>()));
    if (operation == OperationType.DELETE) {
        dataset.stream().filter(q -> q.getGraphName().filter(PreferServerManaged::equals).isPresent()).map(JenaCommonsRDF::toJena).forEach(sink::addQuad);
    } else {
        dataset.stream().filter(q -> q.getGraphName().filter(PreferServerManaged::equals).isPresent()).map(JenaCommonsRDF::toJena).forEach(sink::addQuad);
        dataset.getGraph(PreferUserManaged).ifPresent(g -> g.stream().map(t -> new Quad(toJena(identifier), toJena(t))).forEach(sink::addQuad));
        dataset.getGraph(PreferAudit).ifPresent(g -> g.stream().map(t -> new Quad(getExtIRI(identifier, "audit"), toJena(t))).forEach(sink::addQuad));
        extensions.forEach((ext, graph) -> dataset.getGraph(graph).ifPresent(g -> g.stream().map(t -> new Quad(getExtIRI(identifier, ext), toJena(t))).forEach(sink::addQuad)));
    }
    req.add(new UpdateDataInsert(sink));
    return req;
}
Also used : IdentifierService(org.trellisldp.api.IdentifierService) TrellisRuntimeException(org.trellisldp.api.TrellisRuntimeException) XSD(org.trellisldp.vocabulary.XSD) DeletedResource(org.trellisldp.vocabulary.Trellis.DeletedResource) DatabaseMgr.connectDatasetGraph(org.apache.jena.tdb2.DatabaseMgr.connectDatasetGraph) RDF.type(org.trellisldp.vocabulary.RDF.type) QuadAcc(org.apache.jena.sparql.modify.request.QuadAcc) Resource(org.trellisldp.api.Resource) Collections.singletonList(java.util.Collections.singletonList) SUBJECT(org.trellisldp.triplestore.TriplestoreUtils.SUBJECT) Txn.executeWrite(org.apache.jena.system.Txn.executeWrite) TrellisUtils.normalizeIdentifier(org.trellisldp.api.TrellisUtils.normalizeIdentifier) 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) PreferServerManaged(org.trellisldp.vocabulary.Trellis.PreferServerManaged) Collections.synchronizedList(java.util.Collections.synchronizedList) DC(org.trellisldp.vocabulary.DC) Set(java.util.Set) Literal(org.apache.commons.rdf.api.Literal) Instant(java.time.Instant) CompletionStage(java.util.concurrent.CompletionStage) Stream(java.util.stream.Stream) Var(org.apache.jena.sparql.core.Var) Stream.builder(java.util.stream.Stream.builder) TRELLIS_DATA_PREFIX(org.trellisldp.api.TrellisUtils.TRELLIS_DATA_PREFIX) PostConstruct(javax.annotation.PostConstruct) Optional(java.util.Optional) RDFConnection(org.apache.jena.rdfconnection.RDFConnection) ApplicationScoped(javax.enterprise.context.ApplicationScoped) Query(org.apache.jena.query.Query) FOAF(org.trellisldp.vocabulary.FOAF) Arrays.stream(java.util.Arrays.stream) ElementGroup(org.apache.jena.sparql.syntax.ElementGroup) Instant.now(java.time.Instant.now) NodeFactory.createURI(org.apache.jena.graph.NodeFactory.createURI) ElementNamedGraph(org.apache.jena.sparql.syntax.ElementNamedGraph) RDFTerm(org.apache.commons.rdf.api.RDFTerm) ACL(org.trellisldp.vocabulary.ACL) PreferAccessControl(org.trellisldp.vocabulary.Trellis.PreferAccessControl) UpdateDeleteInsert(org.apache.jena.sparql.modify.request.UpdateDeleteInsert) ElementPathBlock(org.apache.jena.sparql.syntax.ElementPathBlock) Supplier(java.util.function.Supplier) RDF(org.apache.commons.rdf.api.RDF) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) Metadata(org.trellisldp.api.Metadata) Quad(org.apache.jena.sparql.core.Quad) ResourceService(org.trellisldp.api.ResourceService) LDP(org.trellisldp.vocabulary.LDP) DatasetFactory.wrap(org.apache.jena.query.DatasetFactory.wrap) Dataset(org.apache.commons.rdf.api.Dataset) RDFFactory(org.trellisldp.api.RDFFactory) CompletableFuture.runAsync(java.util.concurrent.CompletableFuture.runAsync) RDFConnectionFactory.connect(org.apache.jena.rdfconnection.RDFConnectionFactory.connect) Logger(org.slf4j.Logger) PREDICATE(org.trellisldp.triplestore.TriplestoreUtils.PREDICATE) QuadDataAcc(org.apache.jena.sparql.modify.request.QuadDataAcc) JenaCommonsRDF(org.apache.jena.commonsrdf.JenaCommonsRDF) TriplestoreUtils.getObject(org.trellisldp.triplestore.TriplestoreUtils.getObject) UpdateDeleteWhere(org.apache.jena.sparql.modify.request.UpdateDeleteWhere) IRI(org.apache.commons.rdf.api.IRI) UpdateDataInsert(org.apache.jena.sparql.modify.request.UpdateDataInsert) Node(org.apache.jena.graph.Node) DatasetFactory.createTxnMem(org.apache.jena.query.DatasetFactory.createTxnMem) LoggerFactory.getLogger(org.slf4j.LoggerFactory.getLogger) ConfigProperty(org.eclipse.microprofile.config.inject.ConfigProperty) UpdateRequest(org.apache.jena.update.UpdateRequest) PreferUserManaged(org.trellisldp.vocabulary.Trellis.PreferUserManaged) OBJECT(org.trellisldp.triplestore.TriplestoreUtils.OBJECT) Quad(org.apache.jena.sparql.core.Quad) UpdateDeleteWhere(org.apache.jena.sparql.modify.request.UpdateDeleteWhere) UpdateRequest(org.apache.jena.update.UpdateRequest) UpdateDataInsert(org.apache.jena.sparql.modify.request.UpdateDataInsert) ArrayList(java.util.ArrayList) PreferServerManaged(org.trellisldp.vocabulary.Trellis.PreferServerManaged) QuadDataAcc(org.apache.jena.sparql.modify.request.QuadDataAcc) QuadAcc(org.apache.jena.sparql.modify.request.QuadAcc)

Example 2 with PreferUserManaged

use of org.trellisldp.vocabulary.Trellis.PreferUserManaged in project trellis by trellis-ldp.

the class PutHandler method handleResourceUpdate.

private CompletionStage<ResponseBuilder> handleResourceUpdate(final Dataset mutable, final Dataset immutable, final ResponseBuilder builder, final IRI ldpType) {
    final Metadata.Builder metadata;
    final BinaryMetadata binary;
    // Add user-supplied data
    if (LDP.NonRDFSource.equals(ldpType) && rdfSyntax == null) {
        LOGGER.trace("Successfully checked for bad digest value");
        final String mimeType = getRequest().getContentType() != null ? getRequest().getContentType() : APPLICATION_OCTET_STREAM;
        final IRI binaryLocation = rdf.createIRI(getServices().getBinaryService().generateIdentifier(internalId));
        binary = BinaryMetadata.builder(binaryLocation).mimeType(mimeType).hints(getRequest().getHeaders()).build();
        metadata = metadataBuilder(internalId, ldpType, mutable).binary(binary);
        builder.link(getIdentifier() + "?ext=description", "describedby");
    } else {
        final RDFSyntax s = rdfSyntax != null ? rdfSyntax : TURTLE;
        final IRI ext = getExtensionGraphName();
        final IRI graphName = ext != null ? ext : PreferUserManaged;
        readEntityIntoDataset(graphName, s, mutable);
        // Check the mutable dataset for any constraints
        checkConstraints(mutable, ldpType, s);
        metadata = metadataBuilder(internalId, ldpType, mutable);
        if (getResource() != null) {
            getResource().getBinaryMetadata().ifPresent(metadata::binary);
        }
        binary = null;
    }
    if (getResource() != null) {
        getResource().getContainer().ifPresent(metadata::container);
        metadata.revision(getResource().getRevision());
        LOGGER.debug("Resource {} found in persistence", getIdentifier());
        try (final Stream<Quad> remaining = getResource().stream(getNonCurrentGraphNames())) {
            remaining.forEachOrdered(mutable::add);
        }
    } else if (!createUncontained) {
        getContainer(internalId).ifPresent(metadata::container);
    }
    getAuditQuadData().forEachOrdered(immutable::add);
    LOGGER.trace("Successfully calculated and skolemized immutable data");
    ldpResourceTypes(effectiveLdpType(ldpType)).map(IRI::getIRIString).forEach(type -> {
        LOGGER.trace("Adding link for type {}", type);
        builder.link(type, Link.TYPE);
    });
    LOGGER.trace("Persisting mutable data for {} with data: {}", internalId, mutable);
    final Metadata m = metadata.build();
    return createOrReplace(m, mutable, immutable).thenCompose(future -> persistBinaryContent(binary)).thenCompose(future -> handleUpdateNotification(ldpType, m.getRevision().orElse(null))).thenApply(future -> decorateResponse(builder));
}
Also used : ServiceBundler(org.trellisldp.common.ServiceBundler) TrellisUtils.getContainer(org.trellisldp.api.TrellisUtils.getContainer) HttpUtils.ldpResourceTypes(org.trellisldp.http.impl.HttpUtils.ldpResourceTypes) ClientErrorException(javax.ws.rs.ClientErrorException) Resource(org.trellisldp.api.Resource) CONFIG_HTTP_LDP_MODEL_MODIFICATIONS(org.trellisldp.common.HttpConstants.CONFIG_HTTP_LDP_MODEL_MODIFICATIONS) MediaType(javax.ws.rs.core.MediaType) AS(org.trellisldp.vocabulary.AS) Metadata(org.trellisldp.api.Metadata) APPLICATION_OCTET_STREAM(javax.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM) TURTLE(org.apache.commons.rdf.api.RDFSyntax.TURTLE) HttpUtils.checkRequiredPreconditions(org.trellisldp.http.impl.HttpUtils.checkRequiredPreconditions) Map(java.util.Map) Response.status(javax.ws.rs.core.Response.status) UnsupportedInteractionModel(org.trellisldp.vocabulary.Trellis.UnsupportedInteractionModel) BadRequestException(javax.ws.rs.BadRequestException) UriBuilder(javax.ws.rs.core.UriBuilder) LDP(org.trellisldp.vocabulary.LDP) HttpUtils.exists(org.trellisldp.http.impl.HttpUtils.exists) Dataset(org.apache.commons.rdf.api.Dataset) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) BAD_REQUEST(javax.ws.rs.core.Response.Status.BAD_REQUEST) BinaryMetadata(org.trellisldp.api.BinaryMetadata) TrellisRequest(org.trellisldp.common.TrellisRequest) NotAcceptableException(javax.ws.rs.NotAcceptableException) Logger(org.slf4j.Logger) CONFLICT(javax.ws.rs.core.Response.Status.CONFLICT) NO_CONTENT(javax.ws.rs.core.Response.Status.NO_CONTENT) ConfigProvider.getConfig(org.eclipse.microprofile.config.ConfigProvider.getConfig) HttpUtils.closeDataset(org.trellisldp.http.impl.HttpUtils.closeDataset) Instant(java.time.Instant) List(java.util.List) IRI(org.apache.commons.rdf.api.IRI) CompletionStage(java.util.concurrent.CompletionStage) Stream(java.util.stream.Stream) Quad(org.apache.commons.rdf.api.Quad) RDFSyntax(org.apache.commons.rdf.api.RDFSyntax) IF_MATCH(javax.ws.rs.core.HttpHeaders.IF_MATCH) LoggerFactory.getLogger(org.slf4j.LoggerFactory.getLogger) IF_UNMODIFIED_SINCE(javax.ws.rs.core.HttpHeaders.IF_UNMODIFIED_SINCE) PreferUserManaged(org.trellisldp.vocabulary.Trellis.PreferUserManaged) CREATED(javax.ws.rs.core.Response.Status.CREATED) Link(javax.ws.rs.core.Link) InputStream(java.io.InputStream) IRI(org.apache.commons.rdf.api.IRI) Quad(org.apache.commons.rdf.api.Quad) Metadata(org.trellisldp.api.Metadata) BinaryMetadata(org.trellisldp.api.BinaryMetadata) RDFSyntax(org.apache.commons.rdf.api.RDFSyntax) BinaryMetadata(org.trellisldp.api.BinaryMetadata)

Example 3 with PreferUserManaged

use of org.trellisldp.vocabulary.Trellis.PreferUserManaged 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 PreferUserManaged

use of org.trellisldp.vocabulary.Trellis.PreferUserManaged in project trellis by trellis-ldp.

the class TrellisWebDAV method resourceToMultiStatus.

private Function<Resource, CompletionStage<DavMultiStatus>> resourceToMultiStatus(final Document doc, final IRI identifier, final String location, final String baseUrl, final Session session, final DavPropertyUpdate propertyUpdate) {
    return resource -> {
        final Dataset dataset = rdf.createDataset();
        final Set<IRI> removeProperties = getRemoveProperties(propertyUpdate);
        final DavMultiStatus multistatus = new DavMultiStatus();
        final DavResponse response = new DavResponse();
        final Set<IRI> modifiedProperties = new HashSet<>();
        response.setHref(location);
        // Keep any extension data
        try (final Stream<Quad> stream = resource.stream(extensions.values())) {
            stream.forEach(dataset::add);
        }
        // Filter out any removable properties
        try (final Stream<Quad> stream = resource.stream(PreferUserManaged)) {
            stream.forEach(quad -> {
                if (removeProperties.contains(quad.getPredicate())) {
                    modifiedProperties.add(quad.getPredicate());
                } else {
                    dataset.add(rdf.createQuad(PreferUserManaged, identifier, quad.getPredicate(), quad.getObject()));
                }
            });
        }
        final DavSet set = propertyUpdate.getSet();
        if (set != null) {
            final DavProp prop = set.getProp();
            if (prop != null) {
                Optional.ofNullable(prop.getNodes()).ifPresent(nodes -> nodes.stream().flatMap(elementToQuads(identifier)).forEach(quad -> {
                    modifiedProperties.add(quad.getPredicate());
                    dataset.add(quad);
                }));
            }
        }
        response.setPropStats(modifiedProperties.stream().map(predicate -> {
            final DavPropStat stat = new DavPropStat();
            final DavProp prop = new DavProp();
            prop.setNodes(List.of(doc.createElementNS(namespaceXML(predicate.getIRIString()), localnameXML(predicate.getIRIString()))));
            stat.setProp(prop);
            stat.setStatus(SUCCESS);
            return stat;
        }).collect(toList()));
        multistatus.setDescription("Response to property update request");
        multistatus.setResponses(List.of(response));
        final Dataset immutable = rdf.createDataset();
        services.getAuditService().creation(resource.getIdentifier(), session).stream().map(skolemizeQuads(services.getResourceService(), baseUrl)).forEachOrdered(immutable::add);
        return services.getResourceService().replace(Metadata.builder(resource).build(), dataset).whenComplete((a, b) -> closeDataset(dataset)).thenCompose(future -> services.getResourceService().add(resource.getIdentifier(), immutable)).whenComplete((a, b) -> closeDataset(immutable)).thenCompose(future -> services.getMementoService().put(services.getResourceService(), resource.getIdentifier())).thenRun(() -> services.getNotificationService().emit(new SimpleNotification(location, session.getAgent(), List.of(PROV.Activity, AS.Update), List.of(resource.getInteractionModel()), null))).thenApply(future -> multistatus);
    };
}
Also used : Produces(javax.ws.rs.Produces) WebDAVUtils.recursiveCopy(org.trellisldp.webdav.impl.WebDAVUtils.recursiveCopy) UriBuilder.fromUri(javax.ws.rs.core.UriBuilder.fromUri) SecurityContext(javax.ws.rs.core.SecurityContext) Resource(org.trellisldp.api.Resource) Document(org.w3c.dom.Document) Map(java.util.Map) Response.status(javax.ws.rs.core.Response.status) ACCESS_EXTERNAL_SCHEMA(javax.xml.XMLConstants.ACCESS_EXTERNAL_SCHEMA) DavPropertyUpdate(org.trellisldp.webdav.xml.DavPropertyUpdate) INFINITY(org.trellisldp.webdav.Depth.DEPTH.INFINITY) Set(java.util.Set) Literal(org.apache.commons.rdf.api.Literal) WebDAVUtils.depth1Copy(org.trellisldp.webdav.impl.WebDAVUtils.depth1Copy) SplitIRI.namespaceXML(org.apache.jena.util.SplitIRI.namespaceXML) CompletionStage(java.util.concurrent.CompletionStage) Stream(java.util.stream.Stream) TRELLIS_DATA_PREFIX(org.trellisldp.api.TrellisUtils.TRELLIS_DATA_PREFIX) WebApplicationException(javax.ws.rs.WebApplicationException) UriInfo(javax.ws.rs.core.UriInfo) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) WebDAVUtils.skolemizeQuads(org.trellisldp.webdav.impl.WebDAVUtils.skolemizeQuads) TrellisExtensions(org.trellisldp.common.TrellisExtensions) TrellisUtils.getContainer(org.trellisldp.api.TrellisUtils.getContainer) ArrayList(java.util.ArrayList) Metadata(org.trellisldp.api.Metadata) LdpResource(org.trellisldp.common.LdpResource) GONE(javax.ws.rs.core.Response.Status.GONE) DavPropFind(org.trellisldp.webdav.xml.DavPropFind) FEATURE_SECURE_PROCESSING(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING) LDP(org.trellisldp.vocabulary.LDP) Dataset(org.apache.commons.rdf.api.Dataset) DavProp(org.trellisldp.webdav.xml.DavProp) BinaryMetadata(org.trellisldp.api.BinaryMetadata) SECONDS(java.time.temporal.ChronoUnit.SECONDS) RDFFactory(org.trellisldp.api.RDFFactory) TrellisRequest(org.trellisldp.common.TrellisRequest) ZonedDateTime.ofInstant(java.time.ZonedDateTime.ofInstant) WebDAVUtils.externalUrl(org.trellisldp.webdav.impl.WebDAVUtils.externalUrl) NO_CONTENT(javax.ws.rs.core.Response.Status.NO_CONTENT) PROV(org.trellisldp.vocabulary.PROV) DavRemove(org.trellisldp.webdav.xml.DavRemove) ConfigProperty(org.eclipse.microprofile.config.inject.ConfigProperty) RFC_1123_DATE_TIME(java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME) PreferUserManaged(org.trellisldp.vocabulary.Trellis.PreferUserManaged) CompletableFuture.completedFuture(java.util.concurrent.CompletableFuture.completedFuture) Path(javax.ws.rs.Path) ACCESS_EXTERNAL_DTD(javax.xml.XMLConstants.ACCESS_EXTERNAL_DTD) ClientErrorException(javax.ws.rs.ClientErrorException) APPLICATION_XML(javax.ws.rs.core.MediaType.APPLICATION_XML) Consumes(javax.ws.rs.Consumes) Timed(org.eclipse.microprofile.metrics.annotation.Timed) BadRequestException(javax.ws.rs.BadRequestException) Collectors.toSet(java.util.stream.Collectors.toSet) Context(javax.ws.rs.core.Context) WebDAVUtils.closeDataset(org.trellisldp.webdav.impl.WebDAVUtils.closeDataset) HttpConstants(org.trellisldp.common.HttpConstants) PermitAll(javax.annotation.security.PermitAll) WebDAVUtils.copy(org.trellisldp.webdav.impl.WebDAVUtils.copy) CONFLICT(javax.ws.rs.core.Response.Status.CONFLICT) SimpleNotification(org.trellisldp.common.SimpleNotification) DavResponse(org.trellisldp.webdav.xml.DavResponse) NotFoundException(javax.ws.rs.NotFoundException) Objects(java.util.Objects) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Response(javax.ws.rs.core.Response) DavMultiStatus(org.trellisldp.webdav.xml.DavMultiStatus) UTC(java.time.ZoneOffset.UTC) DAV_NAMESPACE(org.trellisldp.webdav.xml.DavUtils.DAV_NAMESPACE) PostConstruct(javax.annotation.PostConstruct) HttpSession(org.trellisldp.common.HttpSession) Optional(java.util.Optional) SpecialResources(org.trellisldp.api.Resource.SpecialResources) ApplicationScoped(javax.enterprise.context.ApplicationScoped) Request(javax.ws.rs.core.Request) ServiceBundler(org.trellisldp.common.ServiceBundler) Session(org.trellisldp.api.Session) CompletableFuture(java.util.concurrent.CompletableFuture) PreferAccessControl(org.trellisldp.vocabulary.Trellis.PreferAccessControl) Function(java.util.function.Function) RDF(org.apache.commons.rdf.api.RDF) HashSet(java.util.HashSet) Inject(javax.inject.Inject) AS(org.trellisldp.vocabulary.AS) ZERO(org.trellisldp.webdav.Depth.DEPTH.ZERO) Node(org.w3c.dom.Node) Logger(org.slf4j.Logger) Collections.emptySet(java.util.Collections.emptySet) DavPropStat(org.trellisldp.webdav.xml.DavPropStat) Collectors.toList(java.util.stream.Collectors.toList) IRI(org.apache.commons.rdf.api.IRI) Quad(org.apache.commons.rdf.api.Quad) Element(org.w3c.dom.Element) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) LoggerFactory.getLogger(org.slf4j.LoggerFactory.getLogger) DavSet(org.trellisldp.webdav.xml.DavSet) WebDAVUtils.recursiveDelete(org.trellisldp.webdav.impl.WebDAVUtils.recursiveDelete) SplitIRI.localnameXML(org.apache.jena.util.SplitIRI.localnameXML) ONE(org.trellisldp.webdav.Depth.DEPTH.ONE) DavMultiStatus(org.trellisldp.webdav.xml.DavMultiStatus) Set(java.util.Set) Collectors.toSet(java.util.stream.Collectors.toSet) HashSet(java.util.HashSet) Collections.emptySet(java.util.Collections.emptySet) DavSet(org.trellisldp.webdav.xml.DavSet) DavResponse(org.trellisldp.webdav.xml.DavResponse) Dataset(org.apache.commons.rdf.api.Dataset) WebDAVUtils.closeDataset(org.trellisldp.webdav.impl.WebDAVUtils.closeDataset) SimpleNotification(org.trellisldp.common.SimpleNotification) Stream(java.util.stream.Stream) DavSet(org.trellisldp.webdav.xml.DavSet) DavProp(org.trellisldp.webdav.xml.DavProp) DavPropStat(org.trellisldp.webdav.xml.DavPropStat)

Example 5 with PreferUserManaged

use of org.trellisldp.vocabulary.Trellis.PreferUserManaged in project trellis by trellis-ldp.

the class PostHandler method handleResourceCreation.

private CompletionStage<ResponseBuilder> handleResourceCreation(final Dataset mutable, final Dataset immutable, final ResponseBuilder builder) {
    final Metadata metadata;
    final BinaryMetadata binary;
    // Add user-supplied data
    if (ldpType.equals(LDP.NonRDFSource)) {
        final String mimeType = contentType != null ? contentType : APPLICATION_OCTET_STREAM;
        final IRI binaryLocation = rdf.createIRI(getServices().getBinaryService().generateIdentifier(internalId));
        // Persist the content
        binary = BinaryMetadata.builder(binaryLocation).mimeType(mimeType).hints(getRequest().getHeaders()).build();
        metadata = metadataBuilder(internalId, ldpType, mutable).container(parentIdentifier).binary(binary).build();
        builder.link(getIdentifier() + "?ext=description", "describedby");
    } else {
        final RDFSyntax s = rdfSyntax != null ? rdfSyntax : TURTLE;
        readEntityIntoDataset(PreferUserManaged, s, mutable);
        // Check for any constraints
        mutable.getGraph(PreferUserManaged).ifPresent(graph -> checkConstraint(graph, ldpType, s));
        metadata = metadataBuilder(internalId, ldpType, mutable).container(parentIdentifier).build();
        binary = null;
    }
    getAuditQuadData().forEachOrdered(immutable::add);
    return handleResourceCreation(metadata, mutable, immutable).thenCompose(future -> persistBinaryContent(binary)).thenCompose(future -> emitNotification(internalId, AS.Create, ldpType, null)).thenApply(future -> {
        ldpResourceTypes(ldpType).map(IRI::getIRIString).forEach(type -> builder.link(type, Link.TYPE));
        return builder.location(UriBuilder.fromUri(getIdentifier()).build());
    });
}
Also used : DELETE(javax.ws.rs.HttpMethod.DELETE) GET(javax.ws.rs.HttpMethod.GET) ServiceBundler(org.trellisldp.common.ServiceBundler) HttpUtils.ldpResourceTypes(org.trellisldp.http.impl.HttpUtils.ldpResourceTypes) NotAllowedException(javax.ws.rs.NotAllowedException) ClientErrorException(javax.ws.rs.ClientErrorException) Resource(org.trellisldp.api.Resource) MediaType(javax.ws.rs.core.MediaType) AS(org.trellisldp.vocabulary.AS) Metadata(org.trellisldp.api.Metadata) APPLICATION_OCTET_STREAM(javax.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM) GONE(javax.ws.rs.core.Response.Status.GONE) TURTLE(org.apache.commons.rdf.api.RDFSyntax.TURTLE) OPTIONS(javax.ws.rs.HttpMethod.OPTIONS) Map(java.util.Map) Response.status(javax.ws.rs.core.Response.status) UnsupportedInteractionModel(org.trellisldp.vocabulary.Trellis.UnsupportedInteractionModel) BadRequestException(javax.ws.rs.BadRequestException) UriBuilder(javax.ws.rs.core.UriBuilder) LDP(org.trellisldp.vocabulary.LDP) Dataset(org.apache.commons.rdf.api.Dataset) DELETED_RESOURCE(org.trellisldp.api.Resource.SpecialResources.DELETED_RESOURCE) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) BAD_REQUEST(javax.ws.rs.core.Response.Status.BAD_REQUEST) BinaryMetadata(org.trellisldp.api.BinaryMetadata) TrellisRequest(org.trellisldp.common.TrellisRequest) Logger(org.slf4j.Logger) CONFLICT(javax.ws.rs.core.Response.Status.CONFLICT) PATCH(javax.ws.rs.HttpMethod.PATCH) HttpUtils.closeDataset(org.trellisldp.http.impl.HttpUtils.closeDataset) NotFoundException(javax.ws.rs.NotFoundException) HEAD(javax.ws.rs.HttpMethod.HEAD) List(java.util.List) IRI(org.apache.commons.rdf.api.IRI) CompletionStage(java.util.concurrent.CompletionStage) Stream(java.util.stream.Stream) RDFSyntax(org.apache.commons.rdf.api.RDFSyntax) LoggerFactory.getLogger(org.slf4j.LoggerFactory.getLogger) PUT(javax.ws.rs.HttpMethod.PUT) MISSING_RESOURCE(org.trellisldp.api.Resource.SpecialResources.MISSING_RESOURCE) PreferUserManaged(org.trellisldp.vocabulary.Trellis.PreferUserManaged) CREATED(javax.ws.rs.core.Response.Status.CREATED) Link(javax.ws.rs.core.Link) InputStream(java.io.InputStream) IRI(org.apache.commons.rdf.api.IRI) Metadata(org.trellisldp.api.Metadata) BinaryMetadata(org.trellisldp.api.BinaryMetadata) RDFSyntax(org.apache.commons.rdf.api.RDFSyntax) BinaryMetadata(org.trellisldp.api.BinaryMetadata)

Aggregations

Map (java.util.Map)5 CompletionStage (java.util.concurrent.CompletionStage)5 Stream (java.util.stream.Stream)5 Dataset (org.apache.commons.rdf.api.Dataset)5 IRI (org.apache.commons.rdf.api.IRI)5 Logger (org.slf4j.Logger)5 LoggerFactory.getLogger (org.slf4j.LoggerFactory.getLogger)5 Metadata (org.trellisldp.api.Metadata)5 Resource (org.trellisldp.api.Resource)5 LDP (org.trellisldp.vocabulary.LDP)5 PreferUserManaged (org.trellisldp.vocabulary.Trellis.PreferUserManaged)5 List (java.util.List)4 BadRequestException (javax.ws.rs.BadRequestException)4 ClientErrorException (javax.ws.rs.ClientErrorException)4 CONFLICT (javax.ws.rs.core.Response.Status.CONFLICT)4 Response.status (javax.ws.rs.core.Response.status)4 ServiceBundler (org.trellisldp.common.ServiceBundler)4 TrellisRequest (org.trellisldp.common.TrellisRequest)4 AS (org.trellisldp.vocabulary.AS)4 ArrayList (java.util.ArrayList)3