001/**
002 * Copyright 2015 DuraSpace, Inc.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.fcrepo.client.utils;
017
018import java.util.Iterator;
019import org.apache.jena.atlas.lib.Sink;
020import org.apache.jena.riot.lang.SinkTriplesToGraph;
021import org.apache.jena.riot.system.StreamRDFBase;
022
023import com.hp.hpl.jena.graph.Graph;
024import com.hp.hpl.jena.graph.Node;
025import com.hp.hpl.jena.graph.Triple;
026import com.hp.hpl.jena.shared.RandomOrderGraph;
027
028/**
029 * class RDFSinkFilter filtering StreamRDF to Sink.
030 * @author lsitu
031 * @since 2014-08-13
032**/
033public class RDFSinkFilter extends StreamRDFBase {
034    // properties to filter
035    private final Node[] properties ;
036    // destination to send the triples filtered.
037    private final Sink<Triple> dest ;
038
039    private RDFSinkFilter(final Sink<Triple> dest, final Node... properties) {
040        this.dest = dest ;
041        this.properties = new Node[properties.length];
042        for ( int i = 0; i < properties.length; i++) {
043            this.properties[i] = properties[i];
044        }
045    }
046
047    @Override
048    public void triple(final Triple triple) {
049        for ( final Node p : properties ) {
050            if ( Node.ANY == p || triple.getPredicate().equals(p) ) {
051                dest.send(triple);
052            }
053        }
054    }
055
056    @Override
057    public void finish() {
058        // flush the buffered.
059        dest.flush() ;
060    }
061
062    /**
063     * Filter the triples
064     * @param triples Iterator of triples
065     * @param properties Properties to include
066     * @return Graph containing the fitlered triples
067     */
068    public static Graph filterTriples (
069            final Iterator<Triple> triples,
070            final Node... properties) {
071        final Graph filteredGraph = new RandomOrderGraph(RandomOrderGraph.createDefaultGraph());
072        final Sink<Triple> graphOutput = new SinkTriplesToGraph(true, filteredGraph);
073        final RDFSinkFilter rdfFilter = new RDFSinkFilter(graphOutput, properties);
074        rdfFilter.start();
075        while (triples.hasNext()) {
076            final Triple triple = triples.next();
077            rdfFilter.triple(triple);
078        }
079        rdfFilter.finish();
080        return filteredGraph;
081    }
082}