org.apache.jena.query.ResultSet Java Examples

The following examples show how to use org.apache.jena.query.ResultSet. 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: 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 #2
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 #3
Source File: JenaQuery.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Collection<TPatternMatch> evaluate() throws IOException {
	final List<TPatternMatch> matches = new ArrayList<>();

	try (QueryExecution queryExecution = QueryExecutionFactory.create(jenaQuery, driver.getModel())) {
		final ResultSet resultSet = queryExecution.execSelect();

		while (resultSet.hasNext()) {
			final QuerySolution qs = resultSet.next();
			final JenaMatch match = JenaMatch.createMatch(query, qs);
			matches.add((TPatternMatch) match);
		}
	}

	return matches;
}
 
Example #4
Source File: SPARQLDataReader.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private void parseResultSet(DataStore dataStore, MetaData dataStoreMeta, ResultSet resultSet) {
	List<String> columnNames = resultSet.getResultVars();
	for (; resultSet.hasNext();) {
		QuerySolution row = resultSet.nextSolution();
		IRecord record = new Record(dataStore);
		for (int i = 0; i < columnNames.size(); i++) {
			IFieldMetaData fieldMeta = dataStoreMeta.getFieldMeta(i);

			String columnName = columnNames.get(i);
			RDFNode rdfNode = row.get(columnName);
			getValue(rdfNode, record);
			getMetaData(rdfNode, fieldMeta);
		}
		dataStore.appendRecord(record);
	}
}
 
Example #5
Source File: ARQTest.java    From tarql with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testQueryAddValuesInQueryPattern() {
	List<Var> header = vars("a", "b");
	Binding b1 = binding(header, "1", "2");
	Binding b2 = binding(header, "3", "4");

	Query q = QueryFactory.create("SELECT * {}");
	ElementGroup group = new ElementGroup();
	ElementData table = new ElementData();
	table.add(Var.alloc("a"));
	table.add(Var.alloc("b"));
	table.add(b1);
	table.add(b2);
	group.addElement(q.getQueryPattern());
	group.addElement(table);
	q.setQueryPattern(group);
	ResultSet rs = QueryExecutionFactory.create(q, 
			ModelFactory.createDefaultModel()).execSelect();

	assertEquals(Arrays.asList(new String[]{"a","b"}), rs.getResultVars());
	assertTrue(rs.hasNext());
	assertEquals(b1, rs.nextBinding());
	assertTrue(rs.hasNext());
	assertEquals(b2, rs.nextBinding());
	assertFalse(rs.hasNext());
}
 
Example #6
Source File: CombineManifest.java    From incubator-taverna-language with Apache License 2.0 6 votes vote down vote up
private static List<RDFNode> creatingAgentsFor(Resource r) {
	logger.fine("Finding creator of " + r);
	String queryStr = sparqlPrefixes + "SELECT ?agent WHERE { \n" + " { \n"
			+ "  ?r dct:creator [ \n" + "	    rdfs:member ?agent \n"
			+ "  ] \n" + " } UNION { \n" + "   ?r dct:creator ?agent .\n "
			+ "   FILTER NOT EXISTS { ?agent rdfs:member ?member } \n"
			+ " } \n" + "} \n";
	logger.finer(QueryFactory.create(queryStr).toString());
	QueryExecution qexec = QueryExecutionFactory.create(queryStr,
			r.getModel());
	QuerySolutionMap binding = new QuerySolutionMap();
	binding.add("r", r);
	qexec.setInitialBinding(binding);
	ResultSet select = qexec.execSelect();
	List<RDFNode> agents = new ArrayList<>();

	while (select.hasNext()) {
		RDFNode agent = select.next().get("agent");
		logger.fine("Found: " + agent);
		agents.add(agent);
	}
	return agents;
}
 
Example #7
Source File: CombineManifest.java    From incubator-taverna-language with Apache License 2.0 6 votes vote down vote up
private static Resource mboxForAgent(Resource agentResource) {
	logger.fine("Finding mbox of " + agentResource);
	String queryStr = sparqlPrefixes + "SELECT ?mbox WHERE { \n"
			+ "		{ ?agent foaf:mbox ?mbox } \n" + "	UNION  \n"
			+ "		{ ?agent vcard:hasEmail ?mbox } \n" + "	UNION  \n"
			+ "		{ ?agent vcard:email ?email .  \n"
			+ "       BIND(IRI(CONCAT(\"mbox:\", ?email)) AS ?mbox) \n" // legacy
			+ "	    } \n" + "} \n";
	logger.finer(QueryFactory.create(queryStr).toString());
	QueryExecution qexec = QueryExecutionFactory.create(queryStr,
			agentResource.getModel());
	QuerySolutionMap binding = new QuerySolutionMap();
	binding.add("agent", agentResource);
	qexec.setInitialBinding(binding);
	ResultSet select = qexec.execSelect();
	if (select.hasNext()) {
		Resource mbox = select.next().getResource("mbox");
		logger.fine("Found mbox: " + mbox);
		return mbox;
	}
	logger.fine("mbox not found");
	return null;
}
 
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: 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 #10
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 #11
Source File: TestAnnotationTools.java    From incubator-taverna-language with Apache License 2.0 6 votes vote down vote up
@Test
public void componentStuff() throws Exception {
	Dataset dataset = annotations.annotationDatasetFor(component.getMainWorkflow());
	String query = "PREFIX comp: <http://purl.org/DP/components#> "
			+ "SELECT ?fits ?from ?to WHERE { "
			+ " GRAPH ?any { "
			+ "?w comp:fits ?fits ; "
			+ "   comp:migrates ?path . "
			+ "?path comp:fromMimetype ?from ; "
			+ "      comp:toMimetype ?to . "
			+ "  }"
			+ "}";
	
	ResultSet select = QueryExecutionFactory.create(query, dataset).execSelect();
	assertTrue(select.hasNext());
	QuerySolution solution = select.next();
	assertEquals("image/tiff", solution.getLiteral("from").toString());
	assertEquals("image/tiff", solution.getLiteral("to").toString());
	assertEquals("MigrationAction", solution.getResource("fits").getLocalName());
}
 
Example #12
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 #13
Source File: ExTDB5.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) ;
    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() ; }

    // Close the dataset.
    dataset.close();
    
}
 
Example #14
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 #15
Source File: TarqlTest.java    From tarql with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void assertSelect(TarqlQuery tq, Binding... bindings) throws IOException{
	TarqlQueryExecution ex;
	if (csv == null) {
		ex = TarqlQueryExecutionFactory.create(tq, options);
	} else {
		ex = TarqlQueryExecutionFactory.create(tq, InputStreamSource.fromBytes(csv.getBytes("utf-8")), options);
	}
	ResultSet rs = ex.execSelect();
	int counter = 0;
	while (rs.hasNext()) {
		if (counter >= bindings.length) {
			fail("Too many bindings in result; expected " + bindings.length);
		}
		assertEquals(bindings[counter], rs.nextBinding());
		counter += 1;
	}
	assertEquals(bindings.length, counter);
}
 
Example #16
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 #17
Source File: ITER_Call_Select.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
private List<List<NodeValue>> getListNodeValues(ResultSet result) {
    List<String> resultVars = result.getResultVars();
    List<List<NodeValue>> listNodeValues = new ArrayList<>();
    while (result.hasNext()) {
        List<NodeValue> nodeValues = new ArrayList<>();
        QuerySolution sol = result.next();
        for (String var : resultVars) {
            RDFNode rdfNode = sol.get(var);
            if (rdfNode != null) {
                NodeValue n = new NodeValueNode(rdfNode.asNode());
                nodeValues.add(n);
            } else {
                nodeValues.add(null);
            }
        }
        listNodeValues.add(nodeValues);
    }
    return listNodeValues;
}
 
Example #18
Source File: SPARQLExtIteratorFunction.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
private List<List<NodeValue>> getListNodeValues(ResultSet result) {
	List<String> resultVars = result.getResultVars();
	List<List<NodeValue>> listNodeValues = new ArrayList<>();
	while (result.hasNext()) {
		List<NodeValue> nodeValues = new ArrayList<>();
		QuerySolution sol = result.next();
		for (String var : resultVars) {
			RDFNode rdfNode = sol.get(var);
			if (rdfNode != null) {
				NodeValue n = new NodeValueNode(rdfNode.asNode());
				nodeValues.add(n);
			} else {
				nodeValues.add(null);
			}
		}
		listNodeValues.add(nodeValues);
	}
	return listNodeValues;
}
 
Example #19
Source File: LargeInputTest.java    From tarql with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Ignore
@Test public void testInput5GBWithRunawayQuoteButNoQuoteChar() {
	System.out.println("testInput5GBWithRunawayQuoteButNoQuoteChar");
	final int lines = 50000000;
	String query = "SELECT * {}";
	CSVOptions options = new CSVOptions();
	options.setQuoteChar(null);
	ResultSet rs = prepare(query, options, new DummyContentSource(lines) {
		@Override
		public String generateNonHeaderLine(int lineNumber) {
			if (lineNumber == 11111) {
				return super.generateNonHeaderLine(lineNumber) + "\"";
			}
			return super.generateNonHeaderLine(lineNumber);
		}
	}).execSelect();
	int results = consume(rs);
	assertEquals(lines - 1, results);
}
 
Example #20
Source File: QueryOperationTest.java    From robot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Tests a verify with violations.
 *
 * @throws IOException on IO error
 * @throws OWLOntologyStorageException on ontology error
 */
@Test
public void testExecVerifyWithViolations() throws IOException, OWLOntologyStorageException {

  OWLOntology ontology = loadOntology("/simple.owl");
  Dataset dataset = QueryOperation.loadOntologyAsDataset(ontology);
  String allViolations =
      "SELECT ?s ?p ?o\n" + "WHERE {\n" + "    ?s ?p ?o .\n" + "}\n" + "LIMIT 10";

  ResultSet resultSet = QueryOperation.execQuery(dataset, allViolations);
  ResultSetRewindable copy = ResultSetFactory.copyResults(resultSet);
  int resultSize = copy.size();
  copy.reset();

  ByteArrayOutputStream testOut = new ByteArrayOutputStream();
  QueryOperation.writeResult(copy, Lang.CSV, testOut);

  boolean violations = false;
  if (resultSize > 0) {
    violations = true;
  }

  assertTrue(violations);
  assertEquals(7, Lists.newArrayList(testOut.toString().split("\n")).size());
}
 
Example #21
Source File: QueryOperationTest.java    From robot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Tests a verify with no violations.
 *
 * @throws IOException on IO error
 * @throws OWLOntologyStorageException on ontology error
 */
@Test
public void testExecVerifyNoViolations() throws IOException, OWLOntologyStorageException {

  OWLOntology ontology = loadOntology("/simple.owl");
  Dataset dataset = QueryOperation.loadOntologyAsDataset(ontology);
  String allViolations = "SELECT ?s ?p ?o\n" + "WHERE {\n" + "    \n" + "}\n" + "LIMIT 0";

  ResultSet resultSet = QueryOperation.execQuery(dataset, allViolations);
  ResultSetRewindable copy = ResultSetFactory.copyResults(resultSet);
  int resultSize = copy.size();
  copy.reset();

  ByteArrayOutputStream testOut = new ByteArrayOutputStream();
  QueryOperation.writeResult(copy, Lang.CSV, testOut);

  boolean violations = false;
  if (resultSize > 0) {
    violations = true;
  }

  assertFalse(violations);
  assertEquals(1, Lists.newArrayList(testOut.toString().split("\n")).size());
}
 
Example #22
Source File: QueryExecutor.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
public void execSelectPlan(
        final RootPlan plan,
        final List<Binding> newValues,
        final Context context) {
    Objects.nonNull(ContextUtils.getSelectOutput(context));
    final ExecutionKey key = new ExecutionKey(plan, newValues);
    if (++nbselect % 2000 == 00) {
        CacheStats stats = selectExecutions.stats();

        LOG.info("call select " + nbselect + " count " + stats.loadCount() + " - hit count " + stats.hitCount() + " - rate " + stats.hitRate());
    }
    ResultSetRewindable resultSet = selectExecutions.getIfPresent(key);
    if (resultSet != null) {
        resultSet.reset();
    } else {
        ResultSet memResultSet = plan.execSelect(newValues, context);
        resultSet = ResultSetFactory.copyResults(memResultSet);
        selectExecutions.put(key, resultSet);
    }
    ContextUtils.getSelectOutput(context).accept(resultSet);
}
 
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: OneM2MSubscribeUriMapper.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * subscribe uri 가져오기
 * @return List<String>
 */
public List<String> getSubscribeUri() {
	List<String> result = new ArrayList<String>();
	String query = this.makeQueryString();
	String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.dw.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("res").toString().replaceAll(baseuri, ""))));
	}
	return result;
}
 
Example #25
Source File: DBPediaService.java    From baleen with Apache License 2.0 5 votes vote down vote up
private Set<DefaultCandidate> getCandidates(ResultSet rs, String idField, String nameField) {
  Set<DefaultCandidate> candidates = new HashSet<>();
  while (rs.hasNext()) {
    QuerySolution qs = rs.next();
    Map<String, String> fieldsMap = new HashMap<>();
    qs.varNames()
        .forEachRemaining(
            varName -> fieldsMap.put(varName, new DBPediaLanguageString(qs.get(varName)).raw()));
    DBPediaLanguageString id = new DBPediaLanguageString(qs.get(idField));
    DBPediaLanguageString name = new DBPediaLanguageString(qs.get(nameField));
    candidates.add(new DefaultCandidate(id.raw(), name.raw(), fieldsMap));
  }
  return candidates;
}
 
Example #26
Source File: QueryOperationTest.java    From robot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Tests a simple query.
 *
 * @throws IOException on IO error
 * @throws OWLOntologyStorageException on ontology error
 */
@Test
public void testQuery() throws IOException, OWLOntologyStorageException {
  OWLOntology ontology = loadOntology("/simple.owl");
  Dataset dataset = QueryOperation.loadOntologyAsDataset(ontology);
  String query = "SELECT * WHERE { ?s ?p ?o }";
  ResultSet results = QueryOperation.execQuery(dataset, query);
  assertEquals(6, QueryOperation.countResults(results));
}
 
Example #27
Source File: QueryOperationTest.java    From robot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Tests a simple query with imports loaded.
 *
 * @throws IOException on IO error
 * @throws OWLOntologyStorageException on ontology error
 */
@Test
public void testQueryWithDefaultGraph()
    throws IOException, OWLOntologyStorageException, URISyntaxException {
  OWLOntology ontology = loadOntologyWithCatalog("/import_test.owl");
  Dataset dataset = QueryOperation.loadOntologyAsDataset(ontology, true);
  String query =
      "PREFIX owl: <http://www.w3.org/2002/07/owl#>\n"
          + "SELECT * WHERE {\n"
          + "  ?s ?p ?o .\n"
          + "  FILTER NOT EXISTS { ?s ?p owl:Ontology }\n"
          + "}";
  ResultSet results = QueryOperation.execQuery(dataset, query);
  assertEquals(6, QueryOperation.countResults(results));
}
 
Example #28
Source File: QueryOperationTest.java    From robot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Tests a simple query on a named graph.
 *
 * @throws IOException on IO error
 * @throws OWLOntologyStorageException on ontology error
 */
@Test
public void testQueryWithNamedGraph()
    throws IOException, OWLOntologyStorageException, URISyntaxException {
  OWLOntology ontology = loadOntologyWithCatalog("/import_test.owl");
  Dataset dataset = QueryOperation.loadOntologyAsDataset(ontology, true);
  String query =
      "PREFIX robot: <https://github.com/ontodev/robot/robot-core/src/test/resources/>\n"
          + "SELECT * FROM robot:simple.owl WHERE {?s ?p ?o}";
  ResultSet results = QueryOperation.execQuery(dataset, query);
  assertEquals(6, QueryOperation.countResults(results));
}
 
Example #29
Source File: ContextUtils.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
public static Consumer<ResultSet> getSelectOutput(Context context) {
	Consumer<ResultSet> output = context.get(OUTPUT_SELECT);
	if(output != null) {
		return output;
	}
	if(!isRootContext(context)) {
		Context parentContext = (Context) context.get(PARENT_CONTEXT);
		return getSelectOutput(parentContext);
	}
	return null;
}
 
Example #30
Source File: Utils.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static final void getTripleCount() throws Exception {
	String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.sparql.endpoint");

	String queryString = "select  (count(?s) as ?count) where {?s ?p ?o }";
	QueryExecution queryExec = QueryExecutionFactory.sparqlService(serviceURI, queryString);

	ResultSet rs = queryExec.execSelect();

	// 값을 console에 출력함
	ResultSetFormatter.out(rs);
}