package edu.teco.deps.agent.processors;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import org.deri.tarql.CSVQueryExecutionFactory;
import org.deri.tarql.CSVToValues;
import org.deri.tarql.TarqlParser;
import org.deri.tarql.TarqlQuery;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.sparql.algebra.table.TableData;
public class TarqlProcessor implements Processor {
TarqlQuery query;
public TarqlProcessor(Reader queryReader) throws FileNotFoundException {
TarqlParser parser = new TarqlParser(queryReader);
query = parser.getResult();
}
public void process(Reader reader, Writer writer) throws IOException {
CSVToValues transformer = new CSVToValues(reader, false);
TableData table = transformer.read();
Model resultModel = ModelFactory.createDefaultModel();
for (Query q: query.getQueries()) {
// Clone the damn query first, as CSVQueryExecutionFactory is going to alter it
q = q.cloneQuery();
Model previousResults = ModelFactory.createDefaultModel();
previousResults.add(resultModel);
CSVQueryExecutionFactory.setPreviousResults(previousResults);
QueryExecution execution = CSVQueryExecutionFactory.create(table, q);
resultModel.setNsPrefixes(resultModel);
execution.execConstruct(resultModel);
CSVQueryExecutionFactory.resetPreviousResults();
}
resultModel.write(writer, "N-TRIPLE", query.getPrologue().getBaseURI());
writer.flush();
}
}