private static Stream<Quad> generateServerManaged(final Resource resource) { final List<Quad> quads = new ArrayList<>(); quads.add(rdf.createQuad(PreferServerManaged, resource.getIdentifier(), type, resource.getInteractionModel())); quads.add(rdf.createQuad(PreferServerManaged, resource.getIdentifier(), DC.modified, rdf.createLiteral(resource.getModified().toString(), XSD.dateTime))); resource.getBinaryMetadata().ifPresent(b -> { quads.add(rdf.createQuad(PreferServerManaged, resource.getIdentifier(), DC.hasPart, b.getIdentifier())); b.getMimeType().map(mimeType -> rdf.createQuad(PreferServerManaged, b.getIdentifier(), DC.format, rdf.createLiteral(mimeType))).ifPresent(quads::add); }); resource.getContainer() .map(iri -> rdf.createQuad(PreferServerManaged, resource.getIdentifier(), DC.isPartOf, iri)) .ifPresent(quads::add); resource.getMemberOfRelation() .map(iri -> rdf.createQuad(PreferServerManaged, resource.getIdentifier(), LDP.isMemberOfRelation, iri)) .ifPresent(quads::add); resource.getMemberRelation() .map(iri -> rdf.createQuad(PreferServerManaged, resource.getIdentifier(), LDP.hasMemberRelation, iri)) .ifPresent(quads::add); resource.getMembershipResource() .map(iri -> rdf.createQuad(PreferServerManaged, resource.getIdentifier(), LDP.membershipResource, iri)) .ifPresent(quads::add); resource.getInsertedContentRelation() .map(iri -> rdf.createQuad(PreferServerManaged, resource.getIdentifier(), LDP.insertedContentRelation, iri)) .ifPresent(quads::add); return quads.stream(); }
private Stream<Authorization> getAllAuthorizationsFor(final Resource resource, final boolean inherited) { LOGGER.debug("Checking ACL for: {}", resource.getIdentifier()); if (resource.hasAcl()) { try (final WrappedGraph graph = wrap(resource.stream(Trellis.PreferAccessControl).collect(toGraph()))) { final List<Authorization> authorizations = getAuthorizationFromGraph(graph.getGraph()); // Check for any acl:default statements if checking for inheritance if (inherited && authorizations.stream().anyMatch(getInheritedAuth(resource.getIdentifier()))) { return authorizations.stream().filter(getInheritedAuth(resource.getIdentifier())); // If not inheriting, just return the relevant Authorizations in the ACL } else if (!inherited) { return authorizations.stream().filter(getAccessToAuth(resource.getIdentifier())); } } } // Nothing here, check the parent LOGGER.debug("No ACL for {}; looking up parent resource", resource.getIdentifier()); return getContainer(resource.getIdentifier()).map(resourceService::get) .map(CompletionStage::toCompletableFuture).map(CompletableFuture::join) .map(res -> getAllAuthorizationsFor(res, true)).orElseGet(Stream::empty); }
/** * A mutable builder for a {@link Metadata} object. * * @param r the resource * @return a builder for a {@link Metadata} object */ public static Builder builder(final Resource r) { return builder(r.getIdentifier()).interactionModel(r.getInteractionModel()) .container(r.getContainer().orElse(null)) .memberRelation(r.getMemberRelation().orElse(null)) .membershipResource(r.getMembershipResource().orElse(null)) .memberOfRelation(r.getMemberOfRelation().orElse(null)) .insertedContentRelation(r.getInsertedContentRelation().orElse(null)); }
@Override public CompletionStage<Void> put(final Resource resource) { return svc.put(resource).thenAccept(future -> putTime(resource.getIdentifier(), resource.getModified())); }
private Optional<ProducerRecord<String, String>> buildMembershipMessage(final String topic, final IRI resource, final Resource parent, final Dataset dataset) throws Exception { try (final Dataset data = rdf.createDataset()) { if (DirectContainer.equals(parent.getInteractionModel())) { parent.getMembershipResource().ifPresent(member -> { parent.getMemberRelation().ifPresent(relation -> data.add(rdf.createQuad(PreferMembership, member, relation, resource))); parent.getMemberOfRelation().ifPresent(relation -> data.add(rdf.createQuad(PreferMembership, resource, relation, member))); }); } else if (IndirectContainer.equals(parent.getInteractionModel())) { parent.getMembershipResource().ifPresent(member -> parent.getMemberRelation().ifPresent(relation -> parent.getInsertedContentRelation().ifPresent(inserted -> dataset.stream(of(PreferUserManaged), null, inserted, null).sequential().forEachOrdered(q -> data.add(rdf.createQuad(PreferMembership, member, relation, q.getObject())))))); } final Optional<String> key = data.stream(of(PreferMembership), null, null, null).map(Quad::getSubject) .filter(x -> x instanceof IRI).map(x -> (IRI) x).map(IRI::getIRIString).findFirst(); if (key.isPresent()) { dataset.stream(of(PreferAudit), null, null, null).map(auditTypeMapper).forEachOrdered(data::add); return of(new ProducerRecord<>(topic, key.get(), serialize(data))); } return empty(); } }
@Test public void testResource() { assertEquals(0L, mockResource.stream(prefer).count(), "Resource stream has extra triples!"); assertEquals(0L, mockResource.stream(singleton(prefer)).count(), "Resource stream has extra triples!"); assertFalse(mockResource.getMembershipResource().isPresent(), "Membership resource unexpectedly present!"); assertFalse(mockResource.getMemberRelation().isPresent(), "Member relation unexpectedly present!"); assertFalse(mockResource.getMemberOfRelation().isPresent(), "Member of relation unexpectedly present!"); assertFalse(mockResource.getInsertedContentRelation().isPresent(), "Inserted content relation is present!"); assertFalse(mockResource.getBinaryMetadata().isPresent(), "Binary is unexpectedly present!"); assertFalse(mockResource.getExtraLinkRelations().findFirst().isPresent(), "Extra links unexpectedly present!"); assertFalse(mockResource.hasAcl(), "ACL unexpectedly present!"); }
private void setUpResources() { when(mockResource.getInteractionModel()).thenReturn(LDP.RDFSource); when(mockResource.getContainer()).thenReturn(Optional.of(root)); when(mockResource.getIdentifier()).thenReturn(identifier); when(mockResource.getBinaryMetadata()).thenReturn(empty()); when(mockResource.getModified()).thenReturn(time); when(mockResource.getExtraLinkRelations()).thenAnswer(inv -> Stream.empty()); when(mockParent.getInteractionModel()).thenReturn(LDP.Container); when(mockParent.getIdentifier()).thenReturn(root); when(mockParent.getMembershipResource()).thenReturn(empty()); } }
private void setUpRootResource() { when(mockRootResource.hasAcl()).thenReturn(true); when(mockRootResource.getIdentifier()).thenReturn(rootIRI); when(mockRootResource.getInteractionModel()).thenReturn(LDP.BasicContainer); when(mockRootResource.getMembershipResource()).thenReturn(empty()); when(mockRootResource.stream(eq(Trellis.PreferAccessControl))).thenAnswer(inv -> Stream.of( rdf.createTriple(authIRI5, ACL.accessTo, rootIRI), rdf.createTriple(authIRI5, ACL.agent, addisonIRI), rdf.createTriple(authIRI5, ACL.mode, ACL.Read), rdf.createTriple(authIRI5, ACL.mode, ACL.Append), rdf.createTriple(authIRI6, type, ACL.Authorization), rdf.createTriple(authIRI6, ACL.agent, acoburnIRI), rdf.createTriple(authIRI6, ACL.accessTo, rootIRI), rdf.createTriple(authIRI6, ACL.mode, ACL.Append), rdf.createTriple(authIRI8, type, ACL.Authorization), rdf.createTriple(authIRI8, ACL.agent, agentIRI), rdf.createTriple(authIRI8, ACL.accessTo, rootIRI), rdf.createTriple(authIRI8, ACL.mode, ACL.Read), rdf.createTriple(authIRI8, ACL.mode, ACL.Write))); }
private static Stream<Executable> checkResource(final Resource res, final IRI identifier, final IRI ldpType, final boolean hasBinary, final boolean hasAcl, final boolean hasParent) { return Stream.of( () -> assertEquals(identifier, res.getIdentifier(), "Incorrect identifier!"), () -> assertEquals(ldpType, res.getInteractionModel(), "Incorrect interaction model!"), () -> assertEquals(parse(time), res.getModified(), "Incorrect modified date!"), () -> assertEquals(hasBinary, res.getBinaryMetadata().isPresent(), "Unexpected binary presence!"), () -> assertEquals(hasParent, res.getContainer().isPresent(), "Unexpected parent resource!"), () -> assertEquals(hasAcl, res.hasAcl(), "Unexpected ACL presence!")); }
@Test public void testCanRead5() { when(mockSession.getAgent()).thenReturn(addisonIRI); when(mockResourceService.supportedInteractionModels()).thenReturn(singleton(LDP.IndirectContainer)); when(mockParentResource.getInteractionModel()).thenReturn(LDP.IndirectContainer); when(mockParentResource.getMembershipResource()).thenReturn(of(memberIRI)); assertAll("Check user can read all resources", checkAllCanRead()); }
@Test public void testRetrievableResource() { final Instant time = now(); final Quad quad = createQuad(testResourceId2, testResourceId2, testResourceId1, badId); final Resource mockMutable = mock(Resource.class); when(mockMutable.getInteractionModel()).thenReturn(LDP.RDFSource); when(mockMutable.getModified()).thenReturn(time); when(mockMutable.hasAcl()).thenReturn(true); when(mockMutable.getContainer()).thenReturn(empty()); when(mockMutable.stream()).thenAnswer(inv -> Stream.of(quad)); final Resource res = new RetrievableResource(mockMutable, null); assertEquals(LDP.RDFSource, res.getInteractionModel(), "Resource retrieved with wrong interaction model!"); assertEquals(time, res.getModified(), "Resource has wrong modified date!"); assertTrue(res.hasAcl(), "Resource is missing ACL!"); assertFalse(res.getContainer().isPresent(), "Unexpected parent resource!"); assertTrue(res.stream().anyMatch(quad::equals), "Expected quad not present in resource stream!"); }
@Test public void testPersistableResource() { final Instant time = now(); final IRI identifier = createIRI("trellis:identifier"); final Quad quad = createQuad(testResourceId2, testResourceId2, testResourceId1, badId); final Dataset dataset = TrellisUtils.getInstance().createDataset(); dataset.add(quad); final Resource res = new JoiningResourceService.PersistableResource(identifier, LDP.Container, null, dataset); assertEquals(identifier, res.getIdentifier(), "Resource has wrong ID!"); assertEquals(LDP.Container, res.getInteractionModel(), "Resource has wrong LDP type!"); assertFalse(res.getModified().isBefore(time), "Resource modification date predates its creation!"); assertFalse(res.getModified().isAfter(now()), "Resource modification date is too late!"); assertTrue(res.stream().anyMatch(quad::equals), "Expected quad not present in resource stream"); assertFalse(res.getContainer().isPresent(), "Expected no parent container"); assertThrows(UnsupportedOperationException.class, res::hasAcl, "ACL retrieval should throw an exception!"); } }
protected CompletionStage<Void> handleResourceReplacement(final TrellisDataset mutable, final TrellisDataset immutable) { final Metadata.Builder metadata = metadataBuilder(getResource().getIdentifier(), getResource().getInteractionModel(), mutable); getResource().getContainer().ifPresent(metadata::container); getResource().getBinaryMetadata().ifPresent(metadata::binary); // update the resource return allOf( getServices().getResourceService().replace(metadata.build(), mutable.asDataset()).toCompletableFuture(), getServices().getResourceService().add(getResource().getIdentifier(), immutable.asDataset()).toCompletableFuture()); }
@Test public void testGetBinaryDescription2() { when(mockResource.getBinaryMetadata()).thenReturn(of(testBinary)); when(mockResource.getInteractionModel()).thenReturn(LDP.NonRDFSource); when(mockTrellisRequest.getExt()).thenReturn(DESCRIPTION); final GetHandler handler = new GetHandler(mockTrellisRequest, mockBundler, false, true, true, null, null); final Response res = handler.getRepresentation(handler.standardHeaders(handler.initialize(mockResource))) .toCompletableFuture().join().build(); assertAll("Check binary description", checkBinaryDescription(res)); }
@BeforeEach public void setUp() { initMocks(this); when(mockResource.getIdentifier()).thenReturn(identifier); when(mockResource.getModified()).thenReturn(time); when(mockResource.stream()).thenAnswer(inv -> of(quad)); doCallRealMethod().when(mockMementoService).put(any(ResourceService.class), any(IRI.class)); when(mockResourceService.get(any(IRI.class))).thenAnswer(inv -> completedFuture(mockResource)); when(mockMementoService.put(any(Resource.class))).thenReturn(completedFuture(null)); }
@Test public void testInvalidFile() { final IRI identifier = rdf.createIRI(TRELLIS_DATA_PREFIX + "resource"); final File dir = new File(getClass().getResource("/resource.nq").getFile()).getParentFile(); final File file = new File(dir, "nonexistent"); assertFalse(file.exists(), "Non-existent file shouldn't exist!"); final Resource res = new FileResource(identifier, file); assertEquals(identifier, res.getIdentifier(), "Incorrect identifier!"); assertNull(res.getInteractionModel(), "Unexpected interaction model!"); assertEquals(0L, res.stream().count(), "Incorrect total triple count!"); }
private static Stream<Executable> checkResource(final Resource res, final IRI identifier, final IRI ldpType, final Instant time) { return Stream.of( () -> assertNotNull(res, "Missing resource!"), () -> assertEquals(identifier, res.getIdentifier(), "Incorrect identifier!"), () -> assertEquals(ldpType, res.getInteractionModel(), "Incorrect interaction model!"), () -> assertFalse(res.getModified().isBefore(time), "Non-sequential date!"), () -> assertFalse(res.getModified().isAfter(now().plusMillis(5L)), "modification date in the future!")); }
@Test public void testPutIndirectContainerResource() { final EventService myEventService = mock(EventService.class); final Resource mockChildResource = mock(Resource.class); when(mockBundler.getEventService()).thenReturn(myEventService); when(mockResourceService.get(childIdentifier)).thenAnswer(inv -> completedFuture(mockChildResource)); when(mockChildResource.getIdentifier()).thenReturn(childIdentifier); when(mockChildResource.getInteractionModel()).thenReturn(LDP.RDFSource); when(mockRootResource.getInteractionModel()).thenReturn(LDP.IndirectContainer); when(mockRootResource.getMembershipResource()).thenReturn(of(childIdentifier)); final Response res = target(RESOURCE_PATH).request() .put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE)); assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!"); verify(myEventService, times(2)).emit(any()); }
@Test public void testPutUncontainedIndirectContainer() { final EventService myEventService = mock(EventService.class); when(mockBundler.getEventService()).thenReturn(myEventService); when(mockRootResource.getInteractionModel()).thenReturn(LDP.IndirectContainer); when(mockRootResource.getMembershipResource()).thenReturn(of(newresourceIdentifier)); when(mockResource.getContainer()).thenReturn(empty()); final Response res = target(RESOURCE_PATH).request() .put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE)); assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!"); verify(myEventService, times(1)).emit(any()); }