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.transform.transformations;
017
018import static org.fcrepo.kernel.api.RdfCollectors.toModel;
019
020import com.hp.hpl.jena.query.Query;
021import com.hp.hpl.jena.query.QueryExecution;
022import com.hp.hpl.jena.query.QueryExecutionFactory;
023import com.hp.hpl.jena.query.QueryFactory;
024import com.hp.hpl.jena.rdf.model.Model;
025
026import org.apache.commons.io.IOUtils;
027import org.fcrepo.kernel.api.RdfStream;
028import org.fcrepo.transform.Transformation;
029
030import java.io.IOException;
031import java.io.InputStream;
032import java.util.Objects;
033
034/**
035 * SPARQL Query-based transforms
036 *
037 * @author cbeer
038 */
039public class SparqlQueryTransform implements Transformation<QueryExecution> {
040
041    private final InputStream query;
042
043    /**
044     * Construct a new SparqlQueryTransform from the data from
045     * the InputStream
046     * @param query the query
047     */
048    public SparqlQueryTransform(final InputStream query) {
049        this.query = query;
050    }
051
052    @Override
053    public QueryExecution apply(final RdfStream rdfStream) {
054
055        try {
056            final Model model = rdfStream.collect(toModel());
057            final Query sparqlQuery =
058                QueryFactory.create(IOUtils.toString(query));
059
060            return QueryExecutionFactory.create(sparqlQuery, model);
061        } catch (final IOException e) {
062            throw new IllegalStateException(e);
063        }
064    }
065
066    @Override
067    public boolean equals(final Object other) {
068        return other instanceof SparqlQueryTransform && query.equals(((SparqlQueryTransform)other).query);
069    }
070
071    @Override
072    public int hashCode() {
073        return Objects.hashCode(query);
074    }
075}