如何在播放中显示SPARQL查询的输出!视图?

时间:2012-08-25 15:29:26

标签: java playframework-2.0 sparql jena

我正在编写一个应用程序,用户可以上传.rdf-Files,然后在其上执行SPARQL-Queries。现在我被困在如何格式化查询的结果。例如:ASK - 查询输出布尔值和SELECT - 查询返回ResultSet。 CONSTRUCTDESCRIBE返回新的RDF图表 如何在表单中获取给定查询的结果以将其传递给我的视图?在那里,我希望打印出一个HTML表。

为了更好地理解我的问题,我创建了这个简约的代码示例:

import java.io.InputStream;

import com.hp.hpl.jena.*;

public class playground {

    public static void main(String[] args) {

      InputStream in = FileManager.get().open("vc-db-1.rdf");
      Model model = ModelFactory.createDefaultModel();
      model.read(in, null);

      String queryStringSelect = "SELECT ?subject ?predicate ?object WHERE { ?subject ?predicate ?object }";
      String queryStringAsk = "ASK WHERE { ?subject ?predicate ?object }";
      String queryStringDescribe = "DESCRIBE * WHERE { ?subject ?predicate ?object }";
      String queryStringConstruct = "CONSTRUCT { ?subject ?predicate ?object } WHERE { ?subject ?predicate ?object }";

      QueryExecution qe = QueryExecutionFactory.create(queryStringDescribe,
        model);
      Query q = QueryFactory.create(queryStringDescribe);

      int queryType = q.getQueryType();
      switch (queryType) {
      case Query.QueryTypeAsk:
          boolean b = qe.execAsk(); // Result that has to be formatted
          ResultSetFormatter.outputAsTSV(System.out, b);
          break;
      case Query.QueryTypeConstruct:
          model = qe.execConstruct(); // Result that has to be formatted
          model.write(System.out);
          break;
      case Query.QueryTypeDescribe:
          model = qe.execDescribe(); // Result that has to be formatted
          model.write(System.out);
          break;
      case Query.QueryTypeSelect:
          ResultSet results = qe.execSelect(); // Result that has to be
                 // formatted
          ResultSetFormatter.outputAsTSV(System.out, results);
          break;
      }

      model.close();
      qe.close();

    }

}

提及的.rdf文件可以在这里下载:http://jena.apache.org/tutorials/sparql_data/vc-db-1.rdf

1 个答案:

答案 0 :(得分:2)

我终于找到了答案:

我采用ByteArrayOutputStream并使用各种model.write()函数来完成剩下的工作。对于SELECT - 查询,我使用文本表示,因为提供的ResultSetFormatter.outputAsRDF()让我回想起了很多废话。无论如何,这是相关的代码

ByteArrayOutputStream baos = new ByteArrayOutputStream();
...
int queryType = q.getQueryType();
switch (queryType) {
case Query.QueryTypeAsk:
    boolean b = qe.execAsk();
    ResultSetFormatter.outputAsRDF(baos, notation, b);
    retval = baos.toString();
    break;
case Query.QueryTypeConstruct:
    model = qe.execConstruct();
    model.write(baos, notation);
    retval = baos.toString();
    break;
case Query.QueryTypeDescribe:
    model = qe.execDescribe();
    model.write(baos, notation);
    retval = baos.toString();
    break;
case Query.QueryTypeSelect:
    ResultSet results = qe.execSelect();
    ResultSetFormatter.out(baos, results);
    retval = baos.toString();
    break;
}