Как добавить и получить данные с сервера Sesame?

Я знакомлюсь с магазином Sesame Triple и пробую базовые вещи, такие как добавление и извлечение данных. Когда я использую SailRepository, все работает хорошо, но когда я использую http-репозиторий, как показано ниже, я получаю эту ошибку:

 repository initialized
    Exception in thread "main" org.openrdf.repository.http.HTTPQueryEvaluationException: 
        at org.openrdf.repository.http.HTTPTupleQuery.evaluate(HTTPTupleQuery.java:59)
        at servlet.sesame.Test.isStored(Test.java:28)
        at servlet.sesame.Test.ADD(Test.java:33)
    at servlet.sesame.Test.main(Test.java:54)
Caused by: org.openrdf.repository.RepositoryException: 
    at org.openrdf.http.client.HTTPClient.handleHTTPError(HTTPClient.java:953)
    at org.openrdf.http.client.HTTPClient.sendTupleQueryViaHttp(HTTPClient.java:718)
    at org.openrdf.http.client.HTTPClient.getBackgroundTupleQueryResult(HTTPClient.java:602)
    at org.openrdf.http.client.HTTPClient.sendTupleQuery(HTTPClient.java:367)
    at org.openrdf.repository.http.HTTPTupleQuery.evaluate(HTTPTupleQuery.java:53)
    ... 3 more

Вот мой код:

public class Test {


public static boolean isStored(String id, Repository rep) throws RepositoryException, QueryEvaluationException, MalformedQueryException
{
    ValueFactory f = rep.getValueFactory();
    URI testedIdURI = f.createURI("http://example.org/" + id);
    // Check if
    String request ="SELECT ?subject WHERE{<"+ testedIdURI +"> ?predicate ?object}";
    TupleQueryResult reponse = rep.getConnection().prepareTupleQuery(QueryLanguage.SPARQL, request).evaluate();
    return reponse.hasNext();
}

public static void ADD(String id, Repository rep) throws RepositoryException, QueryEvaluationException, MalformedQueryException{
    boolean is = isStored(id,rep);
    if(is){
        System.out.println("already exists");
    }
    else{
        rep.getConnection().add(rep.getValueFactory().createURI("http://example.org/", id), RDF.TYPE,FOAF.PERSON);
        System.out.println(id+" added");
    }
}


public static void main(String[] args) throws RepositoryException,RDFHandlerException, MalformedQueryException, QueryEvaluationException {
    Repository rep = new HTTPRepository("http://localhost:8080/openrdf-workbench/","Test");
    //Repository rep = new SailRepository(new MemoryStore());
    rep.initialize();
    System.out.println("repository initialized");


    ValueFactory f = rep.getValueFactory();
    try{

        ADD("Timon",rep);
        ADD("Pumba",rep);
        ADD("eddy",rep);
        ADD("Pumba",rep);
        ADD("Timon",rep);

    rep.getConnection().add(f.createURI("http://example.org/", "Turin"),RDF.PREDICATE,f.createURI("http://example.org/", "Timon"));
    rep.getConnection().add(f.createURI("http://example.org/", "Turin"),RDF.PREDICATE,f.createURI("http://example.org/", "Timon"));
    rep.getConnection().add(f.createURI("http://example.org/", "Timon"),RDF.PREDICATE, f.createURI("http://example.org/", "eddy"));
    rep.getConnection().add(f.createURI("http://example.org/", "Pumba"),RDF.PREDICATE, f.createURI("http://example.org/", "Timon"));


//  RepositoryResult<Statement> statements = rep.getConnection().getStatements(null, null, null, true);

//  Model model = Iterations.addAll(statements, new LinkedHashModel());

    String request = "SELECT DISTINCT ?object WHERE{<" +f.createURI("http://example.org/", "Timon")+"> <"+ RDF.PREDICATE +"> ?object }";

    rep.getConnection().prepareTupleQuery(QueryLanguage.SPARQL, request);

    TupleQueryResult res = rep.getConnection().prepareTupleQuery(QueryLanguage.SPARQL, request).evaluate();
    String s="";

    while(res.hasNext())
    {
        BindingSet bs = res.next();
        s+="\n " +(bs.getBinding("object").getValue().stringValue());
    }

    System.out.println(s);
}
    finally 
    {
        rep.getConnection().close();
    }
}
}

person user3824844    schedule 29.07.2014    source источник
comment
Дублировано на сайте answer.semanticweb.com: answers.semanticweb.com/questions/29529/   -  person Jeen Broekstra    schedule 30.07.2014


Ответы (1)


В вашем коде есть пара вещей. Непосредственная проблема, вероятно, вызвана этой строкой:

Repository rep = new HTTPRepository("http://localhost:8080/openrdf-workbench/","Test");

Здесь вы используете неверный URL-адрес сервера. Правильный URL-адрес сервера: http://localhost:8080/openrdf-sesame/. Изменение этого должно решить насущную проблему.

Однако помимо этого у меня есть совет, как сделать ваш код более надежным, быстрым и масштабируемым. В своем коде вы передаете объект Repository между методами и создаете новый RepositoryConnection каждый раз, когда выполняете обновление или запрос. Это действительно очень неэффективно, не говоря уже о том, что вы тогда не закрываете никаких соединений.

Поэтому вместо этого я бы порекомендовал вам немного больше повторно использовать объект RepositoryConnection и должным образом закрыть его, когда закончите. Например, вместо:

    rep.getConnection().add(f.createURI("http://example.org/", "Turin"),RDF.PREDICATE,f.createURI("http://example.org/", "Timon"));
rep.getConnection().add(f.createURI("http://example.org/", "Turin"),RDF.PREDICATE,f.createURI("http://example.org/", "Timon"));
rep.getConnection().add(f.createURI("http://example.org/", "Timon"),RDF.PREDICATE, f.createURI("http://example.org/", "eddy"));
rep.getConnection().add(f.createURI("http://example.org/", "Pumba"),RDF.PREDICATE, f.createURI("http://example.org/", "Timon"));

сделать что-то вроде этого:

RepositoryConnection conn = rep.getConnection(); 
try {
   conn.begin(); // start a transaction 
   conn.add(f.createURI("http://example.org/", "Turin"),RDF.PREDICATE,f.createURI("http://example.org/", "Timon"));
   conn.add(f.createURI("http://example.org/", "Turin"),RDF.PREDICATE,f.createURI("http://example.org/", "Timon"));
   conn.add(f.createURI("http://example.org/", "Timon"),RDF.PREDICATE, f.createURI("http://example.org/", "eddy"));
   conn.add(f.createURI("http://example.org/", "Pumba"),RDF.PREDICATE, f.createURI("http://example.org/", "Timon"));
   conn.commit(); 
 } 
 finally {
    conn.close();
 }
person Jeen Broekstra    schedule 29.07.2014