001/*
002 * The contents of this file are subject to the license and copyright
003 * detailed in the LICENSE and NOTICE files at the root of the source
004 * tree.
005 */
006package org.fcrepo.http.commons.api.rdf;
007
008import static java.util.Spliterator.IMMUTABLE;
009import static java.util.Spliterators.spliteratorUnknownSize;
010import static java.util.stream.Stream.concat;
011import static java.util.stream.StreamSupport.stream;
012
013import static org.slf4j.LoggerFactory.getLogger;
014
015import java.util.Map;
016
017import javax.ws.rs.core.UriInfo;
018
019import org.apache.jena.rdf.model.Statement;
020
021import org.fcrepo.kernel.api.models.FedoraResource;
022import org.fcrepo.kernel.api.rdf.DefaultRdfStream;
023import org.fcrepo.kernel.api.RdfStream;
024
025import org.slf4j.Logger;
026import org.springframework.context.ApplicationContext;
027import org.springframework.context.ApplicationContextAware;
028import org.springframework.stereotype.Component;
029
030/**
031 * Utility for injecting HTTP-contextual data into an RdfStream
032 *
033 * @author awoods
034 */
035@Component
036public class HttpTripleUtil implements ApplicationContextAware {
037
038    private static final Logger LOGGER = getLogger(HttpTripleUtil.class);
039
040    private ApplicationContext applicationContext;
041
042    @Override
043    public void setApplicationContext(final ApplicationContext applicationContext) {
044        this.applicationContext = applicationContext;
045    }
046
047    /**
048     * Add additional models to the RDF dataset for the given resource
049     *
050     * @param rdfStream the source stream we'll add named models to
051     * @param resource the FedoraResourceImpl in question
052     * @param uriInfo a JAX-RS UriInfo object to build URIs to resources
053     * @return an RdfStream with the added triples
054     */
055    public RdfStream addHttpComponentModelsForResourceToStream(final RdfStream rdfStream,
056            final FedoraResource resource, final UriInfo uriInfo) {
057
058        LOGGER.debug("Adding additional HTTP context triples to stream");
059        return new DefaultRdfStream(rdfStream.topic(), concat(rdfStream, getUriAwareTripleFactories().entrySet()
060                    .stream().flatMap(e -> {
061            LOGGER.debug("Adding response information using: {}", e.getKey());
062            return stream(spliteratorUnknownSize(e.getValue().createModelForResource(resource, uriInfo)
063                    .listStatements(), IMMUTABLE), false).map(Statement::asTriple);
064        })));
065    }
066
067    private Map<String, UriAwareResourceModelFactory> getUriAwareTripleFactories() {
068        return applicationContext
069                .getBeansOfType(UriAwareResourceModelFactory.class);
070    }
071}