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