org.apache.jena.query.QueryExecution Java Examples

The following examples show how to use org.apache.jena.query.QueryExecution. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PubchemMeshSynonyms.java    From act with GNU General Public License v3.0 7 votes vote down vote up
public String fetchCIDFromInchi(String inchi) {
  // The clone method has its own implementation in the SelectBuilder. Thus safe to use!
  SelectBuilder sb = CID_QUERY_TMPL.clone();
  // The inchi litteral needs to be create with a language tag, otherwise it will not match anything
  // See "Matching Litteral with Language Tags" (https://www.w3.org/TR/rdf-sparql-query/#matchLangTags)
  // for more information
  sb.setVar(Var.alloc("inchi_string"), NodeFactory.createLiteral(inchi, ENGLISH_LANG_TAG));
  Query query = sb.build();

  String result;
  LOGGER.debug("Executing SPARQL query: %s", query.toString());
  try (QueryExecution qexec = QueryExecutionFactory.sparqlService(sparqlService, query)) {
    ResultSet results = qexec.execSelect();
    // TODO: we assume here that there is at most one CID per InChI and return the first CID
    // Improve that behavior so we can stitch together many CID's synonyms.
    if (!results.hasNext()) {
      LOGGER.info("Could not find Pubchem Compound Id for input InChI %s", inchi);
      return null;
    }
    result = results.nextSolution().getResource("inchi_iri").getLocalName();
  }

  String cid = extractCIDFromResourceName(result);
  LOGGER.info("Found Pubchem Compound Id %s for input InChI %s", cid, inchi);
  return cid;
}
 
Example #2
Source File: QueryTestCaseType.java    From shacl with Apache License 2.0 6 votes vote down vote up
public static String createResultSetJSON(String queryString, Model model) {
	CurrentThreadFunctions old = CurrentThreadFunctionRegistry.register(model);
	try {
		Query query = ARQFactory.get().createQuery(model, queryString);
		try(QueryExecution qexec = ARQFactory.get().createQueryExecution(query, model)) {
   			ResultSet actualResults = qexec.execSelect();
   			ByteArrayOutputStream os = new ByteArrayOutputStream();
   			ResultSetFormatter.outputAsJSON(os, actualResults);
               return os.toString("UTF-8");
		}
	} 
	catch (UnsupportedEncodingException e) {
		throw ExceptionUtil.throwUnchecked(e);
	}
	finally {
		CurrentThreadFunctionRegistry.unregister(old);
	}
}
 
Example #3
Source File: SHACLUtil.java    From shacl with Apache License 2.0 6 votes vote down vote up
/**
 * Runs the rule to infer missing rdf:type triples for certain blank nodes.
 * @param model  the input Model
 * @return a new Model containing the inferred triples
 */
public static Model createDefaultValueTypesModel(Model model) {
	String sparql = JenaUtil.getStringProperty(DASH.DefaultValueTypeRule.inModel(model), SH.construct);
	if(sparql == null) {
		throw new IllegalArgumentException("Shapes graph does not include " + TOSH.PREFIX + ":" + DASH.DefaultValueTypeRule);
	}
	Model resultModel = JenaUtil.createMemoryModel();
	MultiUnion multiUnion = new MultiUnion(new Graph[] {
		model.getGraph(),
		resultModel.getGraph()
	});
	Model unionModel = ModelFactory.createModelForGraph(multiUnion);
	Query query = ARQFactory.get().createQuery(model, sparql);
	try(QueryExecution qexec = ARQFactory.get().createQueryExecution(query, unionModel)) {
	    qexec.execConstruct(resultModel);
	    return resultModel;    
	}
}
 
Example #4
Source File: DBPediaService.java    From baleen with Apache License 2.0 6 votes vote down vote up
/**
 * Search DBPedia for candidates with a language restriction on certain variables
 *
 * @param selectVars The placeholders for variables to find eg ?x ?y
 * @param whereClauses An array of StringTriple in Subject, Predicate, Object form
 * @param filterClause Clause String to filter results
 * @param limit The maximum number of Candidates to return
 * @param idField A uniquely identifying field contained in the returned Candidates
 * @param nameField The name field used to find the Candidates
 * @param languageSpecificVars Variables to restrict to the specified language
 * @return a Set of DBPediaCandidates
 * @throws ParseException Exception thrown if the SPARQL query fails to parse
 */
public Set<DefaultCandidate> searchForCandidates(
    String[] selectVars,
    StringTriple[] whereClauses,
    String filterClause,
    int limit,
    String idField,
    String nameField,
    String[] languageSpecificVars)
    throws ParseException {

  Query query = buildQuery(selectVars, whereClauses, filterClause, limit, languageSpecificVars);

  QueryExecution qe = QueryExecutionFactory.sparqlService(DBPEDIA_SPARQL_ENDPOINT, query);

  ResultSet rs = qe.execSelect();

  if (LOGGER.isDebugEnabled()) {
    ResultSet rsToPrint = qe.execSelect();
    LOGGER.debug(ResultSetFormatter.asText(rsToPrint));
  }

  return getCandidates(rs, idField, nameField);
}
 
Example #5
Source File: SPARQLRule.java    From shacl with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(RuleEngine ruleEngine, List<RDFNode> focusNodes, Shape shape) {
	ProgressMonitor monitor = ruleEngine.getProgressMonitor();
	for(RDFNode focusNode : focusNodes) {
		
		if(monitor != null && monitor.isCanceled()) {
			return;
		}

		QuerySolutionMap bindings = new QuerySolutionMap();
		bindings.add(SH.thisVar.getVarName(), focusNode);
		try(QueryExecution qexec = ARQFactory.get().createQueryExecution(query, ruleEngine.getDataset(), bindings)) {
			Iterator<Triple> it = qexec.execConstructTriples();
			while(it.hasNext()) {
				Triple triple = it.next();
				ruleEngine.infer(triple, this, shape);
			}
		}
	}
}
 
Example #6
Source File: PubchemMeshSynonyms.java    From act with GNU General Public License v3.0 6 votes vote down vote up
public Map<PubchemSynonymType, Set<String>> fetchPubchemSynonymsFromCID(String cid) {
  // The clone method has its own implementation in the SelectBuilder. Thus safe to use!
  SelectBuilder sb = PUBCHEM_SYNO_QUERY_TMPL.clone();
  sb.setVar(Var.alloc("compound"), String.format("compound:%s", cid));
  Query query = sb.build();
  LOGGER.debug("Executing SPARQL query: %s", query.toString());
  Map<PubchemSynonymType, Set<String>> map = new HashMap<>();

  try (QueryExecution queryExecution = QueryExecutionFactory.sparqlService(sparqlService, query)) {
    ResultSet results = queryExecution.execSelect();
    while(results.hasNext()) {
      QuerySolution solution = results.nextSolution();
      String cheminfId = solution.getResource("type").getLocalName();
      String synonym = solution.getLiteral("value").getString();
      LOGGER.debug("Found synonym %s with type %s", synonym, cheminfId);
      PubchemSynonymType synonymType = PubchemSynonymType.getByCheminfId(cheminfId);
      Set synonyms = map.get(synonymType);
      if (synonyms == null) {
        synonyms = new HashSet<>();
        map.put(synonymType, synonyms);
      }
      synonyms.add(synonym);
    }
  }
  return map;
}
 
Example #7
Source File: PubchemMeshSynonyms.java    From act with GNU General Public License v3.0 6 votes vote down vote up
public Map<MeshTermType, Set<String>> fetchMeshTermsFromCID(String cid) {
  // The clone method has its own implementation in the SelectBuilder. Thus safe to use!
  SelectBuilder sb = MESH_TERMS_QUERY_TMPL.clone();
  sb.setVar(Var.alloc("compound"), String.format("compound:%s", cid));
  Query query = sb.build();
  LOGGER.debug("Executing SPARQL query: %s", query.toString());
  Map<MeshTermType, Set<String>> map = new HashMap<>();

  try (QueryExecution queryExecution = QueryExecutionFactory.sparqlService(sparqlService, query)) {
    ResultSet results = queryExecution.execSelect();
    while(results.hasNext()) {
      QuerySolution solution = results.nextSolution();
      String conceptLabel = solution.getLiteral("concept_label").getString();
      String lexicalTag = solution.getLiteral("lexical_tag").getString();
      LOGGER.debug("Found term %s with tag %s", conceptLabel, lexicalTag);
      MeshTermType meshTermsType = MeshTermType.getByLexicalTag(lexicalTag);
      Set synonyms = map.get(meshTermsType);
      if (synonyms == null) {
        synonyms = new HashSet<>();
        map.put(meshTermsType, synonyms);
      }
      synonyms.add(conceptLabel);
    }
  }
  return map;
}
 
Example #8
Source File: SHACLSPARQLARQFunction.java    From shacl with Apache License 2.0 6 votes vote down vote up
@Override
   public NodeValue executeBody(Dataset dataset, Model defaultModel, QuerySolution bindings) {
    try( QueryExecution qexec = createQueryExecution(dataset, defaultModel, bindings) ) {
        if(arqQuery.isAskType()) {
            boolean result = qexec.execAsk();
            return NodeValue.makeBoolean(result);
        }
        else {
            ResultSet rs = qexec.execSelect();
            if(rs.hasNext()) {
                QuerySolution s = rs.nextSolution();
                List<String> resultVars = rs.getResultVars();
                String varName = resultVars.get(0);
                RDFNode resultNode = s.get(varName);
                if(resultNode != null) {
                    return NodeValue.makeNode(resultNode.asNode());
                }
            }
            throw new ExprEvalException("Empty result set for SHACL function");
        }
    }
}
 
Example #9
Source File: Validator.java    From Processor with Apache License 2.0 6 votes vote down vote up
public OntModel fixOntModel(OntModel ontModel)
    {
        if (ontModel == null) throw new IllegalArgumentException("Model cannot be null");
        
        OntModel fixedModel = ModelFactory.createOntologyModel(ontModel.getSpecification());
        Query fix = QueryFactory.create("CONSTRUCT\n" +
"{\n" +
"  ?s ?p ?o\n" +
"}\n" +
"WHERE\n" +
"{\n" +
"  ?s ?p ?o\n" +
"  FILTER (!(?p = <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> && ?o = <https://www.w3.org/ns/ldt#Constraint>))\n" +
"}");
        
        try (QueryExecution qex = QueryExecutionFactory.create(fix, ontModel))
        {
            fixedModel.add(qex.execConstruct());
        }
        
        return fixedModel;
    }
 
Example #10
Source File: SPARQLTarget.java    From shacl with Apache License 2.0 6 votes vote down vote up
@Override
public boolean contains(Dataset dataset, RDFNode node) {
	QuerySolutionMap bindings = new QuerySolutionMap();
	bindings.add(SH.thisVar.getVarName(), node);
	if(parameterizableTarget != null) {
		parameterizableTarget.addBindings(bindings);
	}
	if(query.isAskType()) {
		try(QueryExecution qexec = SPARQLSubstitutions.createQueryExecution(query, dataset, bindings)) {
		    return qexec.execAsk();
		}
	}
	else {
		try(QueryExecution qexec = SPARQLSubstitutions.createQueryExecution(query, dataset, bindings)) {
		    ResultSet rs = qexec.execSelect();
		    return rs.hasNext();
		}
	}
}
 
Example #11
Source File: TagRdfUnitTestGenerator.java    From RDFUnit with Apache License 2.0 6 votes vote down vote up
private Set<TestCase> generate(QueryExecutionFactoryModel qef, SchemaSource source, TestGenerator testGenerator) {
    Set<TestCase> tests = new HashSet<>();

    Pattern tgPattern = testGenerator.getPattern();

    Query q = QueryFactory.create(PrefixNSService.getSparqlPrefixDecl() + testGenerator.getQuery());
    try (QueryExecution qe = qef.createQueryExecution(q) ) {
        qe.execSelect().forEachRemaining(result -> {

            Optional<TestCase> tc = generateTestFromResult(testGenerator, tgPattern, result, source);
            tc.ifPresent(tests::add);

        });
    }
    return tests;
}
 
Example #12
Source File: JenaUtil.java    From shacl with Apache License 2.0 6 votes vote down vote up
/**
 * Calls a SPARQL expression and returns the result, using some initial bindings.
 *
 * @param expression     the expression to execute (must contain absolute URIs)
 * @param initialBinding the initial bindings for the unbound variables
 * @param dataset        the query Dataset or null for default
 * @return the result or null
 */
public static Node invokeExpression(String expression, QuerySolution initialBinding, Dataset dataset) {
    if (dataset == null) {
        dataset = ARQFactory.get().getDataset(ModelFactory.createDefaultModel());
    }
    Query query = ARQFactory.get().createExpressionQuery(expression);
    try(QueryExecution qexec = ARQFactory.get().createQueryExecution(query, dataset, initialBinding)) {
        ResultSet rs = qexec.execSelect();
        Node result = null;
        if (rs.hasNext()) {
            QuerySolution qs = rs.next();
            String firstVarName = rs.getResultVars().get(0);
            RDFNode rdfNode = qs.get(firstVarName);
            if (rdfNode != null) {
                result = rdfNode.asNode();
            }
        }
        return result;
    }
}
 
Example #13
Source File: ARQFactory.java    From shacl with Apache License 2.0 6 votes vote down vote up
public QueryExecution createQueryExecution(Query query, Dataset dataset, QuerySolution initialBinding) {
		if(!query.getGraphURIs().isEmpty() || !query.getNamedGraphURIs().isEmpty()) {
			dataset = new FromDataset(dataset, query);
		}
		
		if ( LOG_QUERIES ) {
		    // And the data - can be long.
//    		System.err.println("~~ ~~");
//    		RDFDataMgr.write(System.err, dataset.getDefaultModel(), Lang.TTL);
    		System.err.println("~~ ~~");
    		System.err.println(initialBinding);
    		System.err.println(query);
		}
		
		QueryExecution qexec = QueryExecutionFactoryFilter.get().create(query, dataset, initialBinding);
		adjustQueryExecution(qexec);
		return qexec;
	}
 
Example #14
Source File: ExTDB4.java    From xcurator with Apache License 2.0 6 votes vote down vote up
public static void main(String... argv)
{
    // Direct way: Make a TDB-back Jena model in the named directory.
    String directory = "MyDatabases/DB1" ;
    Dataset dataset = TDBFactory.createDataset(directory) ;
    
    // Potentially expensive query.
    String sparqlQueryString = "SELECT (count(*) AS ?count) { ?s ?p ?o }" ;
    // See http://incubator.apache.org/jena/documentation/query/app_api.html
    
    Query query = QueryFactory.create(sparqlQueryString) ;
    QueryExecution qexec = QueryExecutionFactory.create(query, dataset) ;
    ResultSet results = qexec.execSelect() ;
    ResultSetFormatter.out(results) ;
    qexec.close() ;

    dataset.close();
}
 
Example #15
Source File: DB2DescribeHandler.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
public void describe(Resource r) {
	// Default model.
	DB2Closure.closure(otherModel(r, dataset.getDefaultModel()), false, acc, resources);

	String query = "SELECT ?g { GRAPH ?g { <" + r.getURI() + "> ?p ?o } }";
	QueryExecution qExec = RdfStoreQueryExecutionFactory.create(query,
			dataset);

	ResultSet rs = qExec.execSelect();
	for (; rs.hasNext();) {
		QuerySolution qs = rs.next();
		String gName = qs.getResource("g").getURI(); // mdb for DB2
		Model model = dataset.getNamedModel(gName);
		Resource r2 = otherModel(r, model);
		DB2Closure.closure(r2, false, acc, resources);
	}

	qExec.close();
	
	DB2Closure.closure(r, false, acc, resources);
}
 
Example #16
Source File: LocationMapperAccept.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
public LocationMapperAccept(final Model configurationModel) {
    Query q = QueryFactory.create("PREFIX lm: <http://jena.hpl.hp.com/2004/08/location-mapping#>"
            + "SELECT * WHERE {"
            + "[] lm:mapping ?e ."
            + "?e lm:name ?name ; lm:altName ?alt ."
            + "OPTIONAL { ?e lm:media ?media . } "
            + "}");
    try (QueryExecution exec = QueryExecutionFactory.create(q, configurationModel)) {
        exec.execSelect().forEachRemaining((result) -> {
            String name = null, altName = null, media = null;
            try {
                name = result.getLiteral("name").getString();
                altName = result.getLiteral("alt").getString();
                media = (result.getLiteral("media") == null ? null : result.getLiteral("media").getString());
                altLocations.put(new LookUpRequest(name, media), new LookUpRequest(altName, media));
            } catch (Exception ex) {
                log.debug("Error while reading mapping in configuration model for name " + name + ", alt " + altName + ", media " + media, ex);
            }
        });
    }
}
 
Example #17
Source File: DatasetStatistics.java    From RDFUnit with Apache License 2.0 6 votes vote down vote up
private Map<String, Long> getStats(String sparqlQuery, QueryExecutionFactory qef) {
    Map<String, Long> stats = new HashMap<>();


    try (QueryExecution qe =  qef.createQueryExecution(sparqlQuery))
    {
        qe.execSelect().forEachRemaining( qs -> {

            String s = qs.get("stats").toString();
            int c = 0;
            if (qs.contains("count")) {
                c = qs.get("count").asLiteral().getInt();
            }
            stats.put(s, (long) c);
        });
    }

    return stats;
}
 
Example #18
Source File: DatasetGenerator.java    From NLIWOD with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void updateGoldenAnswers(QueryExecutionFactory qef, IQuestion q) {
	Set<String> uris = new HashSet<>();
	if (null != q && null != q.getSparqlQuery() && !q.getSparqlQuery().contains("ASK")) {
		try (QueryExecution qe = qef.createQueryExecution(q.getSparqlQuery())) {
			ResultSet rs = qe.execSelect();
			while (rs.hasNext()) {
				QuerySolution qs = rs.next();

				RDFNode node = qs.get("uri");

				if (node != null && node.isResource()) {
					uris.add(node.asResource().getURI());
				}
			}
		}
		q.setGoldenAnswers(uris);
	} else {// TODO what happens if q is null?
	}

}
 
Example #19
Source File: TarqlQueryExecution.java    From tarql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public ResultSet execSelect() {
	//TODO check only first query. right?
	Query q = getFirstQuery();
	modifyQuery(q, table);
	QueryExecution ex = createQueryExecution(q, ModelFactory.createDefaultModel());
	return ex.execSelect();
}
 
Example #20
Source File: SHACLUtil.java    From shacl with Apache License 2.0 5 votes vote down vote up
/**
 * Gets any locally-defined label for a given property.
 * The labels are expected to be attached to shapes associated with a given
 * context resource (instance).
 * That context resource may for example be the subject of the current UI form.
 * @param property  the property to get the label of
 * @param context  the context instance
 * @return the local label or null if it should fall back to a global label
 */
public static String getLocalPropertyLabel(Resource property, Resource context) {
	QuerySolutionMap binding = new QuerySolutionMap();
	binding.add("arg1", property);
	binding.add("arg2", context);
	try(QueryExecution qexec = ARQFactory.get().createQueryExecution(propertyLabelQuery, property.getModel(), binding)) {
	    ResultSet rs = qexec.execSelect();
	    if(rs.hasNext()) {
	        return rs.next().get("label").asLiteral().getLexicalForm();
	    }
	}
	return null;
}
 
Example #21
Source File: ExTDB_Txn1.java    From xcurator with Apache License 2.0 5 votes vote down vote up
public static void execQuery(String sparqlQueryString, Dataset dataset)
{
    Query query = QueryFactory.create(sparqlQueryString) ;
    QueryExecution qexec = QueryExecutionFactory.create(query, dataset) ;
    try {
        ResultSet results = qexec.execSelect() ;
        for ( ; results.hasNext() ; )
        {
            QuerySolution soln = results.nextSolution() ;
            int count = soln.getLiteral("count").getInt() ;
            System.out.println("count = "+count) ;
        }
      } finally { qexec.close() ; }
}
 
Example #22
Source File: SPARQLSubstitutions.java    From shacl with Apache License 2.0 5 votes vote down vote up
public static QueryExecution createQueryExecution(Query query, Dataset dataset, QuerySolution bindings) {
	if(USE_TRANSFORM && bindings != null) {
		Map<Var,Node> substitutions = new HashMap<Var,Node>();
		Iterator<String> varNames = bindings.varNames();
		while(varNames.hasNext()) {
			String varName = varNames.next();
			substitutions.put(Var.alloc(varName), bindings.get(varName).asNode());
		}
		Query newQuery = JenaUtil.queryWithSubstitutions(query, substitutions);
		return ARQFactory.get().createQueryExecution(newQuery, dataset);
	}
	else {
		return ARQFactory.get().createQueryExecution(query, dataset, bindings);
	}
}
 
Example #23
Source File: DeltaEx06_LocalDatasetToFuseki.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
public static void main2(String ...args) {
    // ---- Fuseki server with patch operation.
    int PORT = 2020 ;
    // In-memory dataset
    DatasetGraph dsgFuseki = DatasetGraphFactory.createTxnMem();

    String serviceName = "patch";
    FusekiServer server = fusekiServerWithPatch("/ds", PORT, dsgFuseki, serviceName);
    server.start();

    // ---- Destination for changes is the Fuseki patch opration.
    String url = "http://localhost:"+PORT+"/ds/"+serviceName;

    RDFChanges changeSender = DeltaClientLib.destination(url);
    // In the case of http/https URLs, this is done with
    //    RDFChanges changeSender = new RDFChangesHTTP(url);

    // ---- Local dataset.
    DatasetGraph dsgLocal = DatasetGraphFactory.createTxnMem();
    // Combined datasetgraph and changes.
    // Changes will be POSTed to the URL.
    DatasetGraph dsg = RDFPatchOps.changes(dsgLocal, changeSender);

    // ---- Do something. Read in data.ttl inside a transaction.
    // (data.ttl is in src/main/resources/)
    Txn.executeWrite(dsg,
        ()->RDFDataMgr.read(dsg, "data.ttl")
        );

    // ---- Query Fuseki
    RDFConnection conn = RDFConnectionFactory.connect("http://localhost:"+PORT+"/ds");
    try( QueryExecution qExec = conn.query("PREFIX ex: <http://example.org/> SELECT * { ?s ?p ?o }") ) {
        ResultSet rs = qExec.execSelect();
        ResultSetFormatter.out(rs, qExec.getQuery());
    }
}
 
Example #24
Source File: RdfStoreQueryExecutionFactory.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
public static QueryExecution create(String sparql, Model model, OWLQLSPARQLCompiler compiler) {
	checkArg(model);

	return new DB2QueryExecutionImpl((com.ibm.research.rdf.store.jena.Query)
			RdfStoreQueryFactory.create(sparql),
			(DB2Graph) model.getGraph(), compiler);

}
 
Example #25
Source File: IOUtils.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
public static Model getModelFromQueryFactory(QueryExecutionFactory qef) {
    if (qef instanceof QueryExecutionFactoryModel) {
        return ((QueryExecutionFactoryModel) qef).getModel();
    } else {
        try (QueryExecution qe = qef.createQueryExecution(" CONSTRUCT ?s ?p ?o WHERE { ?s ?p ?o } ")) {
            return qe.execConstruct();
        }
    }
}
 
Example #26
Source File: JenaDriver.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected boolean ask(final String askQuery) {
	try (QueryExecution queryExecution = QueryExecutionFactory.create(askQuery, model)) {
		final boolean result = queryExecution.execAsk();
		return result;
	}
}
 
Example #27
Source File: ShaclSimpleTestExecutor.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
@Override
protected Collection<TestCaseResult> executeSingleTest(TestSource testSource, TestCase testCase) throws TestCaseExecutionException {

    Collection<TestCaseResult> testCaseResults = new ArrayList<>();


    try (QueryExecution qe = testSource.getExecutionFactory().createQueryExecution(queryGenerationFactory.getSparqlQuery(testCase)))
    {

        qe.execSelect().forEachRemaining( qs -> {

            RDFNode focusNode = testCase.getFocusNode(qs);
            assert(focusNode != null);

            String message = testCase.getResultMessage();
            if (qs.contains("message")) {
                message = qs.get("message").toString();
            }
            RLOGLevel logLevel = testCase.getLogLevel();

            testCaseResults.add(new ShaclLiteTestCaseResultImpl(testCase.getElement(), logLevel, message, focusNode));
        });
    } catch (QueryExceptionHTTP e) {
        checkQueryResultStatus(e);
    }

    return testCaseResults;

}
 
Example #28
Source File: TestDeltaFusekiGood.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
@Test
public void update_1() {
    // Do an update on one server ...
    conn1.update(PREFIX+"INSERT DATA { :s :p 'update_1' }");
    // And see it on the other server ...
    try ( QueryExecution qExec = conn2.query(PREFIX+"ASK { :s :p 'update_1'}") ) {
        Assert.assertEquals(true, qExec.execAsk());
    }
}
 
Example #29
Source File: EntitySPARQLReader.java    From JedAIToolkit with Apache License 2.0 5 votes vote down vote up
private void readEndpoint(String endpointUrl) throws IOException {
    //read each ntriples
    //get spo, create a separate profile for each separate subject,
    //with Attribute=predicate and Value=object
    final String sparqlQueryString1 = "select ?a ?b ?c where {?a ?b ?c}";

    final Query query = QueryFactory.create(sparqlQueryString1);
    try (QueryExecution qexec = QueryExecutionFactory.sparqlService(endpointUrl, query)) {
        final ResultSet results = qexec.execSelect();
        //ResultSetFormatter.out(System.out, results, query);
        //results = qexec.execSelect();
        
        while (results.hasNext()) {
            final QuerySolution qs = results.next();
            
            final String sub = qs.get("a").toString();
            final String pred = qs.get("b").toString();
            final String obj = qs.get("c").toString();
            if (attributesToExclude.contains(pred)) {
                continue;
            }
            
            //if already exists a profile for the subject, simply add po as <Att>-<Value>
            EntityProfile entityProfile = urlToEntity.get(sub);
            if (entityProfile == null) {
                entityProfile = new EntityProfile(sub);
                entityProfiles.add(entityProfile);
                urlToEntity.put(sub, entityProfile);
            }
            
            if (!obj.isEmpty()) {
                entityProfile.addAttribute(pred, obj);
            }
        }
    }
    //ResultSetFormatter.out(System.out, results, query);
    //results = qexec.execSelect();
}
 
Example #30
Source File: OneM2MSubscribeUriMapper.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public List<String> getSubscribeUri() {
	List<String> result = new ArrayList<String>();
	String query = this.makeQueryString();
	String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.sparql.endpoint");
	String baseuri = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.uri");
	QueryExecution queryExec = QueryExecutionFactory.sparqlService(serviceURI, query);
	ResultSet rs = queryExec.execSelect();
	for (; rs.hasNext();) {
		QuerySolution qs = rs.nextSolution();
		result.add(getProperContainerType(
				new String(qs.get("uri").toString().replaceAll(baseuri, ""))));
	}
	return result;
}