Search in sources :

Example 41 with ResultSet

use of org.apache.jena.query.ResultSet in project opentheso by miledrousset.

the class AlignmentQuery method queryDBPedia.

/**
 * Cette fonction permet de récupérer les alignements présents sur DBPedia
 * pour un concept passé en paramètre
 *
 * @param idC
 * @param idTheso
 * @param lexicalValue
 * @param lang
 * @param source
 * @return
 */
public ArrayList<NodeAlignment> queryDBPedia(String idC, String idTheso, String lexicalValue, String lang, String source) {
    listeAlign = new ArrayList<>();
    if (lexicalValue.contains(" ")) {
        lexicalValue = lexicalValue.substring(0, lexicalValue.indexOf(" "));
    }
    lexicalValue = String.valueOf(lexicalValue.charAt(0)).toUpperCase() + lexicalValue.substring(1);
    String sparqlQueryString1 = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>" + "PREFIX dbpedia-owl: <http://dbpedia.org/ontology/>" + "PREFIX foaf: <http://xmlns.com/foaf/0.1/>" + "SELECT * WHERE {" + "       ?s rdfs:label ?label ." + "       ?s rdfs:comment ?comment ." + "       ?s dbpedia-owl:thumbnail ?thumbnail ." + "       ?s foaf:isPrimaryTopicOf ?primaryTopicOf ." + "       FILTER(regex(?s,\"resource/" + lexicalValue + "*\"))" + "       FILTER(lang(?label) = \"" + lang + "\")" + "       FILTER(lang(?comment) = \"" + lang + "\")" + "   }";
    // System.out.println(sparqlQueryString1);
    Query query = QueryFactory.create(sparqlQueryString1);
    QueryExecution qexec = QueryExecutionFactory.sparqlService("http://dbpedia.org/sparql", query);
    ResultSet results = qexec.execSelect();
    while (results.hasNext()) {
        QuerySolution qs = results.next();
        NodeAlignment na = new NodeAlignment();
        na.setInternal_id_concept(idC);
        na.setInternal_id_thesaurus(idTheso);
        na.setConcept_target(qs.get("label").toString());
        na.setDef_target(qs.get("comment").toString());
        na.setThesaurus_target(source);
        na.setUri_target(qs.get("primaryTopicOf").toString());
        listeAlign.add(na);
    }
    qexec.close();
    return listeAlign;
}
Also used : NodeAlignment(mom.trd.opentheso.bdd.helper.nodes.NodeAlignment) Query(org.apache.jena.query.Query) QuerySolution(org.apache.jena.query.QuerySolution) ResultSet(org.apache.jena.query.ResultSet) QueryExecution(org.apache.jena.query.QueryExecution)

Example 42 with ResultSet

use of org.apache.jena.query.ResultSet in project opentheso by miledrousset.

the class AlignmentQuery method queryBNF.

// private getAlignementFromSkos(){
// }
// //////////////////////////////////////
// //////////////////////////////////////
// ////                     /////////////
// ////        SPARQL       /////////////
// ////                     /////////////
// //////////////////////////////////////
// //////////////////////////////////////
/**
 * cette fonction permet de récuperer les alignements de la BNF
 * requête de type Sparql
 * @param idC
 * @param idTheso
 * @param lexicalValue
 * @param lang
 * @param requete
 * @param source
 * @return
 */
public ArrayList<NodeAlignment> queryBNF(String idC, String idTheso, String lexicalValue, String lang, String requete, String source) {
    listeAlign = new ArrayList<>();
    // lexicalValue = lexicalValue.replaceAll(" ", "%20");
    requete = requete.replace("##lang##", "\"" + lang + "\"");
    if (lexicalValue.contains(" ")) {
        String[] valueTemp = lexicalValue.split(" ");
        boolean first = true;
        for (String valuetemp : valueTemp) {
            requete = requete.substring(0, requete.length() - 1);
            if (first) {
                requete = requete.replace("##value##", valuetemp.trim());
                first = false;
            } else {
                requete = requete.concat(" && regex(?value, \"" + valuetemp.trim() + "\",\"i\")");
            }
        }
        requete = requete + ")";
    } else {
        requete = requete.replace("##value##", "\"" + lexicalValue + "\"");
    }
    /*requete = "PREFIX skos: <http://www.w3.org/2004/02/skos/core#>" +
                " PREFIX xml: <http://www.w3.org/XML/1998/namespace>" +
                " SELECT ?instrument ?prop ?value" +
                " where {  <http://data.bnf.fr/ark:/12148/cb119367821> skos:narrower+ ?instrument.  ?instrument ?prop ?value.  FILTER( (regex(?prop,skos:prefLabel) || regex(?prop,skos:altLabel))  && regex(?value, \"cornemuse\",\"i\"))   filter(lang(?value) =\"fr\")} LIMIT 10";
      */
    // System.out.println(requete);
    Query query = QueryFactory.create(requete);
    QueryExecution qexec = QueryExecutionFactory.sparqlService("http://data.bnf.fr/sparql", query);
    ResultSet results = qexec.execSelect();
    while (results.hasNext()) {
        QuerySolution qs = results.next();
        NodeAlignment na = new NodeAlignment();
        na.setInternal_id_concept(idC);
        na.setInternal_id_thesaurus(idTheso);
        na.setConcept_target(qs.get("value").toString());
        // qs.get("comment").toString());
        na.setDef_target("");
        na.setThesaurus_target(source);
        na.setUri_target(qs.get("instrument").toString());
        listeAlign.add(na);
    }
    qexec.close();
    return listeAlign;
}
Also used : NodeAlignment(mom.trd.opentheso.bdd.helper.nodes.NodeAlignment) Query(org.apache.jena.query.Query) QuerySolution(org.apache.jena.query.QuerySolution) ResultSet(org.apache.jena.query.ResultSet) QueryExecution(org.apache.jena.query.QueryExecution)

Example 43 with ResultSet

use of org.apache.jena.query.ResultSet in project jena by apache.

the class Service method exec.

/**
     * Executes a service operator
     * 
     * @param op
     *            Service
     * @param context
     *            Context
     * @return Query iterator of service results
     */
public static QueryIterator exec(OpService op, Context context) {
    if (context != null && context.isFalse(serviceAllowed))
        throw new QueryExecException("SERVICE execution disabled");
    if (!op.getService().isURI())
        throw new QueryExecException("Service URI not bound: " + op.getService());
    // This relies on the observation that the query was originally correct,
    // so reversing the scope renaming is safe (it merely restores the
    // algebra expression).
    // Any variables that reappear should be internal ones that were hidden
    // by renaming in the first place.
    // Any substitution is also safe because it replaced variables by
    // values.
    Op opRemote = Rename.reverseVarRename(op.getSubOp(), true);
    // JENA-494 There is a bug here that the renaming means that if this is
    // deeply nested and joined to other things at the same level of you end
    // up with the variables being disjoint and the same results
    // The naive fix for this is to map the variables visible in the inner
    // operator to those visible in the rewritten operator
    // There may be some cases where the re-mapping is incorrect due to
    // deeply nested SERVICE clauses
    Map<Var, Var> varMapping = new HashMap<>();
    Set<Var> originalVars = OpVars.visibleVars(op);
    Set<Var> remoteVars = OpVars.visibleVars(opRemote);
    boolean requiresRemapping = false;
    for (Var v : originalVars) {
        if (v.getName().contains("/")) {
            // A variable which was scope renamed so has a different name
            String origName = v.getName().substring(v.getName().lastIndexOf('/') + 1);
            Var remoteVar = Var.alloc(origName);
            if (remoteVars.contains(remoteVar)) {
                varMapping.put(remoteVar, v);
                requiresRemapping = true;
            }
        } else {
            // A variable which does not have a different name
            if (remoteVars.contains(v))
                varMapping.put(v, v);
        }
    }
    // Explain.explain("HTTP", opRemote, context) ;
    Query query;
    //@formatter:off
    // Comment (for the future?)
    //        if ( false )
    //        {
    //            // ***** Interacts with substitution.
    //            Element el = op.getServiceElement().getElement() ;
    //            if ( el instanceof ElementSubQuery )
    //                query = ((ElementSubQuery)el).getQuery() ;
    //            else
    //            {
    //                query = QueryFactory.create() ;
    //                query.setQueryPattern(el) ;
    //                query.setResultVars() ;
    //            }
    //        }
    //        else
    //@formatter:on
    query = OpAsQuery.asQuery(opRemote);
    Explain.explain("HTTP", query, context);
    String uri = op.getService().getURI();
    HttpQuery httpQuery = configureQuery(uri, context, query);
    InputStream in = httpQuery.exec();
    // Read the whole of the results now.
    // Avoids the problems with calling back into the same system e.g.
    // Fuseki+SERVICE <http://localhost:3030/...>
    ResultSet rs = ResultSetFactory.fromXML(in);
    QueryIterator qIter = QueryIter.materialize(new QueryIteratorResultSet(rs));
    // And close connection now, not when qIter is closed.
    IO.close(in);
    // nested SERVICE clauses
    if (requiresRemapping) {
        qIter = QueryIter.map(qIter, varMapping);
    }
    return qIter;
}
Also used : Op(org.apache.jena.sparql.algebra.Op) OpAsQuery(org.apache.jena.sparql.algebra.OpAsQuery) Query(org.apache.jena.query.Query) HashMap(java.util.HashMap) Var(org.apache.jena.sparql.core.Var) InputStream(java.io.InputStream) QueryExecException(org.apache.jena.query.QueryExecException) QueryIteratorResultSet(org.apache.jena.sparql.engine.iterator.QueryIteratorResultSet) QueryIterator(org.apache.jena.sparql.engine.QueryIterator) QueryIteratorResultSet(org.apache.jena.sparql.engine.iterator.QueryIteratorResultSet) ResultSet(org.apache.jena.query.ResultSet)

Example 44 with ResultSet

use of org.apache.jena.query.ResultSet in project jena by apache.

the class rset method exec.

@Override
protected void exec() {
    ResultSet rs = modInput.getResultSet();
    modOutput.printResultSet(rs, null);
}
Also used : ResultSet(org.apache.jena.query.ResultSet)

Example 45 with ResultSet

use of org.apache.jena.query.ResultSet in project jena by apache.

the class QueryEngineTest method testSelectAllType.

@Test
public void testSelectAllType() {
    final SecurityEvaluator eval = new MockSecurityEvaluator(true, true, true, true, true, true) {

        @Override
        public boolean evaluate(Object principal, final Action action, final Node graphIRI, final Triple triple) {
            if (triple.getSubject().isURI() && triple.getSubject().getURI().equals("http://example.com/resource/1")) {
                return false;
            }
            return super.evaluate(principal, action, graphIRI, triple);
        }
    };
    final SecuredModel model = Factory.getInstance(eval, "http://example.com/securedModel", baseModel);
    try {
        String query = "SELECT ?s ?p ?o WHERE " + " { ?s ?p ?o } ";
        try (QueryExecution qexec = QueryExecutionFactory.create(query, model)) {
            final ResultSet results = qexec.execSelect();
            int count = 0;
            for (; results.hasNext(); ) {
                count++;
                results.nextSolution();
            }
            // 2x 3 values + type triple
            Assert.assertEquals(8, count);
        }
        query = "SELECT ?s ?p ?o WHERE " + " { GRAPH ?g {?s ?p ?o } }";
        try (QueryExecution qexec = QueryExecutionFactory.create(query, model)) {
            final ResultSet results = qexec.execSelect();
            int count = 0;
            for (; results.hasNext(); ) {
                count++;
                results.nextSolution();
            }
            // 2x 3 values + type triple
            // no named graphs so no results.
            Assert.assertEquals(0, count);
        }
    } finally {
        model.close();
    }
}
Also used : Triple(org.apache.jena.graph.Triple) MockSecurityEvaluator(org.apache.jena.permissions.MockSecurityEvaluator) Node(org.apache.jena.graph.Node) ResultSet(org.apache.jena.query.ResultSet) SecurityEvaluator(org.apache.jena.permissions.SecurityEvaluator) MockSecurityEvaluator(org.apache.jena.permissions.MockSecurityEvaluator) SecuredModel(org.apache.jena.permissions.model.SecuredModel) QueryExecution(org.apache.jena.query.QueryExecution) Test(org.junit.Test)

Aggregations

ResultSet (org.apache.jena.query.ResultSet)79 Test (org.junit.Test)43 BuilderResultSet (org.apache.jena.sparql.sse.builders.BuilderResultSet)33 BaseTest (org.apache.jena.atlas.junit.BaseTest)27 QueryExecution (org.apache.jena.query.QueryExecution)18 QuerySolution (org.apache.jena.query.QuerySolution)15 ByteArrayInputStream (java.io.ByteArrayInputStream)13 Query (org.apache.jena.query.Query)11 ResultSetRewindable (org.apache.jena.query.ResultSetRewindable)11 ByteArrayOutputStream (java.io.ByteArrayOutputStream)10 QueryIterator (org.apache.jena.sparql.engine.QueryIterator)8 ResultSetStream (org.apache.jena.sparql.engine.ResultSetStream)8 ArrayList (java.util.ArrayList)7 Node (org.apache.jena.graph.Node)7 Model (org.apache.jena.rdf.model.Model)6 ConfigTest (org.apache.jena.tdb.ConfigTest)6 DatasetGraph (org.apache.jena.sparql.core.DatasetGraph)5 Var (org.apache.jena.sparql.core.Var)5 NodeAlignment (mom.trd.opentheso.bdd.helper.nodes.NodeAlignment)4 Binding (org.apache.jena.sparql.engine.binding.Binding)4