Search in sources :

Example 1 with BinaryMetadata

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

the class DBResourceService method updateResource.

private static int updateResource(final Handle handle, final Metadata metadata, final Dataset dataset, final Instant time, final boolean isDelete) {
    handle.execute("DELETE FROM resource WHERE subject = ?", metadata.getIdentifier().getIRIString());
    final String query = "INSERT INTO resource (subject, interaction_model, modified, deleted, is_part_of, acl, " + "ldp_member, ldp_membership_resource, ldp_has_member_relation, ldp_is_member_of_relation, " + "ldp_inserted_content_relation, binary_location, binary_format) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    // Set ldp:insertedContentRelation only for LDP-IC and LDP-DC resources
    final String icr = asList(LDP.DirectContainer, LDP.IndirectContainer).contains(metadata.getInteractionModel()) ? metadata.getInsertedContentRelation().orElse(LDP.MemberSubject).getIRIString() : null;
    try (final Update update = handle.createUpdate(query).bind(0, metadata.getIdentifier().getIRIString()).bind(1, metadata.getInteractionModel().getIRIString()).bind(2, time.toEpochMilli()).bind(3, isDelete).bind(4, metadata.getContainer().map(IRI::getIRIString).orElse(null)).bind(5, dataset.contains(of(PreferAccessControl), null, null, null)).bind(6, metadata.getMembershipResource().map(TrellisUtils::normalizeIdentifier).map(IRI::getIRIString).orElse(null)).bind(7, metadata.getMembershipResource().map(IRI::getIRIString).orElse(null)).bind(8, metadata.getMemberRelation().map(IRI::getIRIString).orElse(null)).bind(9, metadata.getMemberOfRelation().map(IRI::getIRIString).orElse(null)).bind(10, icr).bind(11, metadata.getBinary().map(BinaryMetadata::getIdentifier).map(IRI::getIRIString).orElse(null)).bind(12, metadata.getBinary().flatMap(BinaryMetadata::getMimeType).orElse(null))) {
        return update.executeAndReturnGeneratedKeys("id").mapTo(Integer.class).one();
    }
}
Also used : IRI(org.apache.commons.rdf.api.IRI) Update(org.jdbi.v3.core.statement.Update) BinaryMetadata(org.trellisldp.api.BinaryMetadata)

Example 2 with BinaryMetadata

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

the class TriplestoreResourceServiceTest method testPutLdpNr.

@Test
void testPutLdpNr() {
    final TriplestoreResourceService svc = new TriplestoreResourceService();
    svc.rdfConnection = connect(wrap(toJena(rdf.createDataset())));
    svc.idService = idService;
    svc.initialize();
    final IRI binaryIdentifier = rdf.createIRI("foo:binary");
    final Dataset dataset = rdf.createDataset();
    final BinaryMetadata binary = BinaryMetadata.builder(binaryIdentifier).mimeType("text/plain").build();
    dataset.add(Trellis.PreferUserManaged, resource, DC.title, rdf.createLiteral("title"));
    dataset.add(Trellis.PreferAudit, rdf.createBlankNode(), type, AS.Create);
    final Instant later = meanwhile();
    assertDoesNotThrow(() -> allOf(svc.create(builder(resource).interactionModel(LDP.NonRDFSource).container(root).binary(binary).build(), dataset).toCompletableFuture(), svc.touch(root).toCompletableFuture()).join(), "Unsuccessful create operation!");
    allOf(svc.get(resource).thenAccept(checkResource(later, LDP.NonRDFSource, 1L, 1L, 0L)).toCompletableFuture(), svc.get(resource).thenAccept(res -> assertAll("Check binary", checkBinary(res, binaryIdentifier, "text/plain"))).toCompletableFuture(), svc.get(root).thenAccept(checkRoot(later, 1L)).toCompletableFuture()).join();
    final IRI resource3 = rdf.createIRI(TRELLIS_DATA_PREFIX + "resource/notachild");
    dataset.clear();
    dataset.add(Trellis.PreferUserManaged, resource3, DC.title, rdf.createLiteral("title"));
    dataset.add(Trellis.PreferAudit, rdf.createBlankNode(), type, AS.Create);
    final Instant evenLater = meanwhile();
    assertDoesNotThrow(() -> svc.create(builder(resource3).interactionModel(LDP.RDFSource).build(), dataset).toCompletableFuture().join(), "Unsuccessful create operation!");
    allOf(svc.get(resource3).thenAccept(res -> {
        assertAll("Check resource", checkResource(res, resource3, LDP.RDFSource, evenLater));
        assertAll("Check resource stream", checkResourceStream(res, 1L, 0L, 1L, 0L, 0L));
        assertFalse(res.getBinaryMetadata().isPresent(), "Unexpected binary metadata!");
    }).toCompletableFuture(), svc.get(root).thenAccept(checkRoot(later, 1L)).toCompletableFuture(), svc.get(root).thenAccept(checkPredates(evenLater)).toCompletableFuture(), svc.get(root).thenAccept(res -> assertFalse(res.getBinaryMetadata().isPresent(), "unexpected binary metadata!")).toCompletableFuture(), svc.get(resource).thenAccept(checkResource(later, LDP.NonRDFSource, 1L, 1L, 0L)).toCompletableFuture(), svc.get(resource).thenAccept(checkPredates(evenLater)).toCompletableFuture()).join();
}
Also used : IdentifierService(org.trellisldp.api.IdentifierService) XSD(org.trellisldp.vocabulary.XSD) Optional.of(java.util.Optional.of) RDF.type(org.trellisldp.vocabulary.RDF.type) Resource(org.trellisldp.api.Resource) SKOS(org.trellisldp.vocabulary.SKOS) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) JenaCommonsRDF.toJena(org.apache.jena.commonsrdf.JenaCommonsRDF.toJena) Map(java.util.Map) RDFLinkDataset(org.apache.jena.rdflink.RDFLinkDataset) DELETED_RESOURCE(org.trellisldp.api.Resource.SpecialResources.DELETED_RESOURCE) Awaitility.await(org.awaitility.Awaitility.await) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) DC(org.trellisldp.vocabulary.DC) Literal(org.apache.commons.rdf.api.Literal) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Instant(java.time.Instant) Awaitility.setDefaultPollInterval(org.awaitility.Awaitility.setDefaultPollInterval) Test(org.junit.jupiter.api.Test) Stream(java.util.stream.Stream) TRELLIS_DATA_PREFIX(org.trellisldp.api.TrellisUtils.TRELLIS_DATA_PREFIX) RDFConnection(org.apache.jena.rdfconnection.RDFConnection) RDFConnectionAdapter(org.apache.jena.rdflink.RDFConnectionAdapter) RDFLinkHTTP(org.apache.jena.rdflink.RDFLinkHTTP) RDFS(org.trellisldp.vocabulary.RDFS) Instant.now(java.time.Instant.now) Mock(org.mockito.Mock) Metadata.builder(org.trellisldp.api.Metadata.builder) RDF(org.apache.commons.rdf.api.RDF) AS(org.trellisldp.vocabulary.AS) CompletableFuture.allOf(java.util.concurrent.CompletableFuture.allOf) LDP(org.trellisldp.vocabulary.LDP) DatasetFactory.wrap(org.apache.jena.query.DatasetFactory.wrap) Dataset(org.apache.commons.rdf.api.Dataset) Trellis(org.trellisldp.vocabulary.Trellis) BinaryMetadata(org.trellisldp.api.BinaryMetadata) DefaultIdentifierService(org.trellisldp.api.DefaultIdentifierService) RDFFactory(org.trellisldp.api.RDFFactory) RDFConnectionFactory.connect(org.apache.jena.rdfconnection.RDFConnectionFactory.connect) BlankNode(org.apache.commons.rdf.api.BlankNode) Predicate.isEqual(java.util.function.Predicate.isEqual) File(java.io.File) ExecutionException(java.util.concurrent.ExecutionException) Consumer(java.util.function.Consumer) Mockito(org.mockito.Mockito) IRI(org.apache.commons.rdf.api.IRI) PROV(org.trellisldp.vocabulary.PROV) Executable(org.junit.jupiter.api.function.Executable) Assertions(org.junit.jupiter.api.Assertions) UpdateRequest(org.apache.jena.update.UpdateRequest) MISSING_RESOURCE(org.trellisldp.api.Resource.SpecialResources.MISSING_RESOURCE) IRI(org.apache.commons.rdf.api.IRI) RDFLinkDataset(org.apache.jena.rdflink.RDFLinkDataset) Dataset(org.apache.commons.rdf.api.Dataset) Instant(java.time.Instant) BinaryMetadata(org.trellisldp.api.BinaryMetadata) Test(org.junit.jupiter.api.Test)

Example 3 with BinaryMetadata

use of org.trellisldp.api.BinaryMetadata 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 4 with BinaryMetadata

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

the class CassandraBuildingService method parse.

default Resource parse(final Row metadata, final Logger log, final IRI id) {
    if (metadata == null) {
        log.debug("{} was not found.", id);
        return MISSING_RESOURCE;
    }
    log.debug("{} was found, computing metadata.", id);
    final IRI ixnModel = metadata.get("interactionModel", IRI.class);
    log.debug("Found interactionModel = {} for resource {}", ixnModel, id);
    final IRI container = metadata.get("container", IRI.class);
    log.debug("Found container = {} for resource {}", container, id);
    final IRI binaryId = metadata.get("binaryIdentifier", IRI.class);
    log.debug("Found binaryIdentifier = {} for resource {}", binaryId, id);
    final String mimeType = metadata.getString("mimetype");
    log.debug("Found mimeType = {} for resource {}", mimeType, id);
    final Instant modified = metadata.get("modified", Instant.class);
    log.debug("Found modified = {} for resource {}", modified, id);
    final Dataset dataset = CassandraIOUtils.parse(metadata.getString("quads"));
    log.debug("Found dataset = {} for resource {}", dataset, id);
    final BinaryMetadata binary = binaryId != null ? BinaryMetadata.builder(binaryId).mimeType(mimeType).build() : null;
    final Set<IRI> graphs = dataset.getGraphNames().filter(IRI.class::isInstance).map(IRI.class::cast).filter(isEqual(Trellis.PreferUserManaged).or(isEqual(Trellis.PreferServerManaged)).negate()).collect(toSet());
    final Metadata meta = Metadata.builder(id).container(container).interactionModel(ixnModel).metadataGraphNames(graphs).binary(binary).build();
    return new CassandraResource(meta, modified, dataset);
}
Also used : IRI(org.apache.commons.rdf.api.IRI) Dataset(org.apache.commons.rdf.api.Dataset) Instant(java.time.Instant) BinaryMetadata(org.trellisldp.api.BinaryMetadata) Metadata(org.trellisldp.api.Metadata) BinaryMetadata(org.trellisldp.api.BinaryMetadata)

Example 5 with BinaryMetadata

use of org.trellisldp.api.BinaryMetadata in project trellis-cassandra by ajs6f.

the class CassandraMementoService method put.

@Override
public CompletionStage<Void> put(Resource r) {
    IRI id = r.getIdentifier();
    IRI ixnModel = r.getInteractionModel();
    IRI container = r.getContainer().orElse(null);
    Optional<BinaryMetadata> binary = r.getBinaryMetadata();
    IRI binaryIdentifier = binary.map(BinaryMetadata::getIdentifier).orElse(null);
    String mimeType = binary.flatMap(BinaryMetadata::getMimeType).orElse(null);
    Dataset data = r.dataset();
    Instant modified = r.getModified();
    UUID creation = Uuids.timeBased();
    log.debug("Writing Memento for {} at time: {}", id, modified);
    return mementoize.execute(ixnModel, mimeType, container, data, modified, binaryIdentifier, creation, id);
}
Also used : IRI(org.apache.commons.rdf.api.IRI) Dataset(org.apache.commons.rdf.api.Dataset) Instant(java.time.Instant) UUID(java.util.UUID) BinaryMetadata(org.trellisldp.api.BinaryMetadata)

Aggregations

IRI (org.apache.commons.rdf.api.IRI)15 BinaryMetadata (org.trellisldp.api.BinaryMetadata)15 Instant (java.time.Instant)9 Dataset (org.apache.commons.rdf.api.Dataset)7 Resource (org.trellisldp.api.Resource)7 InputStream (java.io.InputStream)6 Map (java.util.Map)5 Test (org.junit.jupiter.api.Test)5 LDP (org.trellisldp.vocabulary.LDP)5 List (java.util.List)4 Stream (java.util.stream.Stream)4 Binary (org.trellisldp.api.Binary)4 CompletionStage (java.util.concurrent.CompletionStage)3 ClientErrorException (javax.ws.rs.ClientErrorException)3 Link (javax.ws.rs.core.Link)3 APPLICATION_OCTET_STREAM (javax.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM)3 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)3 UriBuilder (javax.ws.rs.core.UriBuilder)3 Quad (org.apache.commons.rdf.api.Quad)3 RDF (org.apache.commons.rdf.api.RDF)3