1

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

4

1 回答 1

2

我终于找到了答案:

我拿了一个 ByteArrayOutputStream 并使用各种model.write()函数来完成其余的工作。对于SELECT-Query,我使用文本表示,因为提供的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;
}
于 2012-08-28T10:20:58.383 回答