如何在游戏中显示sparql查询的输出!查看?

j9per5c4  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(317)

我正在编写一个应用程序,用户可以上传.rdf文件,然后在上面执行sparql查询。现在我被困在如何格式化查询的结果。例如:一个 ASK -查询输出布尔值和 SELECT -查询返回结果集。 CONSTRUCT 以及 DESCRIBE 返回一个新的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

flvlnr44

flvlnr441#

我终于找到了答案:
我取一个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;
}

相关问题