org.apache.jena.query.QueryExecutionFactory Java Examples

The following examples show how to use org.apache.jena.query.QueryExecutionFactory. 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: 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 #3
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 #4
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 #5
Source File: CustomQueryValidator.java    From rdflint with MIT License 6 votes vote down vote up
@Override
public void validateTripleSet(LintProblemSet problems, String file, List<Triple> tripeSet) {
  if (this.getParameters().getRules() == null) {
    return;
  }
  // execute sparql & custom validation
  Graph g = Factory.createGraphMem();
  tripeSet.forEach(g::add);
  Model m = ModelFactory.createModelForGraph(g);

  this.getParameters().getRules().stream()
      .filter(r -> file.matches(r.getTarget()))
      .forEach(r -> {
        Query query = QueryFactory.create(r.getQuery());
        QueryExecution qe = QueryExecutionFactory.create(query, m);

        Binding binding = new Binding();
        binding.setVariable("rs", qe.execSelect());
        binding.setVariable("log", new ProblemLogger(this, problems, file, r.getName()));
        GroovyShell shell = new GroovyShell(binding, new CompilerConfiguration());
        shell.evaluate(r.getValid());
      });
}
 
Example #6
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 #7
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 #8
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 #9
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 #10
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 #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: 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 #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: 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: TripleIndexCreatorContext.java    From AGDISTIS with GNU Affero General Public License v3.0 6 votes vote down vote up
public String sparql(String subject) {

		// First query takes the most specific class from a given resource.
		String ontology_service = endpoint;

		String endpointsSparql = "select ?label where {<" + subject
				+ "> <http://www.w3.org/2000/01/rdf-schema#label> ?label FILTER (lang(?label) = 'en')} LIMIT 100";

		Query sparqlQuery = QueryFactory.create(endpointsSparql, Syntax.syntaxARQ);
		QueryEngineHTTP qexec = (QueryEngineHTTP) QueryExecutionFactory.sparqlService(ontology_service, sparqlQuery);
		qexec.setModelContentType(WebContent.contentTypeRDFXML);
		ResultSet results = qexec.execSelect();
		String property = null;
		while (results.hasNext()) {
			QuerySolution qs = results.next();
			property = qs.getLiteral("?label").getLexicalForm();
		}
		return property;

	}
 
Example #16
Source File: DBpediaMappingValidator.java    From RDFUnit with Apache License 2.0 6 votes vote down vote up
public List<MappingDomainError> getErrorListFromModel(Model model) {
    List<MappingDomainError> mappingDomainErrors = new ArrayList<>();
    try  ( QueryExecution qe = QueryExecutionFactory.create(SPARQL_QUERY, model))
    {

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

            String mapping = qs.get("mapping").toString();
            String error = qs.get("error").toString();
            String missing = qs.get("missing").toString();
            String predicate = qs.get("predicate").toString();

            mappingDomainErrors.add(new MappingDomainError(mapping, predicate, error, missing));

        } );
    }
    return mappingDomainErrors;
}
 
Example #17
Source File: ARQTest.java    From tarql with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testQuerySetValuesDataBlock() {
	List<Var> header = vars("a", "b");
	Binding b1 = binding(header, "1", "2");
	Binding b2 = binding(header, "3", "4");

	Query q = QueryFactory.create("SELECT * {}");
	q.setValuesDataBlock(header, bindings(b1, b2));
	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 #18
Source File: Test.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void updateTest() {
		// Add a new book to the collection
//		String service = "http://219.248.137.7:13030/icbms/update";
//		UpdateRequest ur = UpdateFactory
//				.create(""
//						+ "delete  { <http://www.pineone.com/campus/TemperatureObservationValue_LB0001> <http://data.nasa.gov/qudt/owl/qudt#hasNumericValue>  ?value . } "
//						+ "insert  { <http://www.pineone.com/campus/TemperatureObservationValue_LB0001> <http://data.nasa.gov/qudt/owl/qudt#hasNumericValue>  \"19\" . } " //<-- 19대신 여기 온도를 넣어주세
//						+ "WHERE   { <http://www.pineone.com/campus/TemperatureObservationValue_LB0001> <http://data.nasa.gov/qudt/owl/qudt#hasNumericValue> ?value . }");
//		UpdateProcessor up = UpdateExecutionFactory.createRemote(ur, service);
//		up.execute();

		// Query the collection, dump output
//		String service1 = "http://219.248.137.7:13030/icbms/";
//		QueryExecution qe = QueryExecutionFactory.sparqlService(service1,
//				"SELECT * WHERE {<http://www.pineone.com/campus/Student_S00001> ?r ?y} limit 20 ");
//
//		ResultSet results = qe.execSelect();
//		ResultSetFormatter.out(System.out, results);
//		qe.close();
		Model model = ModelFactory.createDefaultModel();
		Statement s = model.createStatement(model.createResource("ex:e1"),model.createProperty("ex:p1"), ResourceFactory.createTypedLiteral(new String("0.6")));
		model.add(s);
		String query = "select * {?s ?p ?o }";
		QueryExecution qe = QueryExecutionFactory.create(query, model);
		ResultSet results = qe.execSelect();
		ResultSetFormatter.out(System.out, results);
		qe.close();
	}
 
Example #19
Source File: ERDDataset2.java    From gerbil with GNU Affero General Public License v3.0 5 votes vote down vote up
private List<Marking> findMarkings(String[] text, File annFile) throws GerbilException {
	List<Marking> markings = new ArrayList<Marking>();
	try (BufferedReader breader = new BufferedReader(new InputStreamReader(
			new FileInputStream(annFile), Charset.forName("UTF-8")))) {
		String line;
		
		while ((line = breader.readLine()) != null) {
			if(line.isEmpty()){
				continue;
			}
			String[] annotation = line.split("\t");
			int searchID = getTrecID(text[0]);
			int annoID = getTrecID(annotation[0]);
			if(searchID == annoID){
				int start = text[1].indexOf(annotation[3]);
				int length = annotation[3].length();
				
				//FIXME time consuming!
                   String freebaseID = annotation[2].substring(1, annotation[2].length()).replace("/",".");
                   Query query = QueryFactory.create(queryTemp.replace("%%v%%", freebaseID));
                   QueryExecution qexec = QueryExecutionFactory.createServiceRequest(DBPEDIA_SERVICE, query);
                   String uri =  qexec.execSelect().next().getResource("s").getURI();
                   
				
				markings.add(new NamedEntity(start, length, uri));
			}
			else if(annoID > searchID){
				//There is no annotation for the given text
				break;
			}
		}
	} catch (IOException e) {
		throw new GerbilException("Exception while reading dataset.", e,
				ErrorTypes.DATASET_LOADING_ERROR);
	}

	return markings;
}
 
Example #20
Source File: JenaDriver.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
public Collection<QuerySolution> runQuery(final RailwayQuery query, final String queryDefinition) throws IOException {
	final Collection<QuerySolution> results = new ArrayList<>();
	try (QueryExecution queryExecution = QueryExecutionFactory.create(queryDefinition, model)) {
		final ResultSet resultSet = queryExecution.execSelect();

		while (resultSet.hasNext()) {
			final QuerySolution qs = resultSet.next();
			results.add(qs);
		}
	}

	return results;
}
 
Example #21
Source File: DBpediaToWikiId.java    From gerbil with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * The Wikipedia Id or -1 if the Id couldn't be retrieved.
 * 
 * FIXME The method throws an exception for "http://DBpedia.org/resource/Origin_of_the_name_"Empire_State"". this
 * might be happen because of the quotes inside the URI.
 * 
 * @param dbpediaUri
 * @return
 */
@Deprecated
public static int getIdFromDBpedia(String dbpediaUri) {
    int id = -1;
    ParameterizedSparqlString query = new ParameterizedSparqlString(
            "SELECT ?id WHERE { ?dbpedia dbo:wikiPageID ?id .}", prefixes);
    query.setIri("dbpedia", dbpediaUri);
    QueryExecution qexec = null;
    try {
        qexec = QueryExecutionFactory.create(query.asQuery(),
                model);
    } catch (QueryParseException e) {
        LOGGER.error("Got a bad dbpediaUri \"" + dbpediaUri
                + "\" which couldn't be parse inside of a SPARQL query. Returning -1.", e);
        return id;
    }
    ResultSet result = qexec.execSelect();
    if (result.hasNext()) {
        id = result.next().get("id").asLiteral().getInt();
        return id;
    }
    qexec = QueryExecutionFactory.sparqlService(
            "http://dbpedia.org/sparql", query.asQuery());
    result = qexec.execSelect();
    if (result.hasNext()) {
        id = result.next().get("id").asLiteral().getInt();
        model.add(new StatementImpl(model.createResource(dbpediaUri), model
                .createProperty("http://dbpedia.org/ontology/wikiPageID"),
                model.createTypedLiteral(id)));
        return id;
    }

    model.add(new StatementImpl(model.createResource(dbpediaUri), model
            .createProperty("http://dbpedia.org/ontology/wikiPageID"),
            model.createTypedLiteral(id)));
    return id;
}
 
Example #22
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);
}
 
Example #23
Source File: SPARQLDataProxy.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public IDataStore load(IDataReader dataReader) {
	logger.debug("IN");
	IDataStore dataStore = null;

	try (QueryExecution queryExecution = QueryExecutionFactory.sparqlService(sparqlEndpoint, sparqlQuery, defaultGraphIRI)) {
		ResultSet resultSet = executeSPARQLQuery(queryExecution);
		dataStore = readResultSet(dataReader, dataStore, resultSet);
	} catch (Exception e) {
		throw new SpagoBIRuntimeException("An error occurred while executing SPARQL query", e);
	}
	logger.debug("OUT");
	return dataStore;
}
 
Example #24
Source File: RdfDataManager.java    From rdf2neo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Take an existing {@link CypherEntity} and adds the properties that can be mapped from the underlining TDB by means 
 * of a property query, like {@link CyNodeLoadingHandler#getNodePropsSparql()}, or 
 * {@link CyRelationLoadingHandler#getRelationPropsSparql()}.
 * 
 * It doesn't do anything if the query is null.
 * 
 */
protected void addCypherProps ( CypherEntity cyEnt, String propsSparql )
{
	ensureOpen ();		
	Dataset dataSet = this.getDataSet ();
	
	QuerySolutionMap params = new QuerySolutionMap ();
	params.add ( "iri", dataSet.getUnionModel().getResource ( cyEnt.getIri () ) );

	// It may be omitted, if you don't have any property except the IRI.
	if ( propsSparql == null ) return;
	
	Query qry = SparqlUtils.getCachedQuery ( propsSparql );
	Function<String, String> propIdConverter = this.getCyPropertyIdConverter ();
	
	boolean wasInTnx = dataSet.isInTransaction ();
	if ( !wasInTnx ) dataSet.begin ( ReadWrite.READ );
	try
	{
		QueryExecution qx = QueryExecutionFactory.create ( qry, dataSet, params );
		qx.execSelect ().forEachRemaining ( row ->
		{
			String propName = this.getCypherId ( row.get ( "name" ), propIdConverter );
			if ( propName == null ) throw new IllegalArgumentException ( 
				"Null property name for " + cyEnt.getIri () 
			);
			
			String propValue = JENAUTILS.literal2Value ( row.getLiteral ( "value" ) ).get ();
			cyEnt.addPropValue ( propName, propValue );
		});
	}
	finally {
		if ( !wasInTnx && dataSet.isInTransaction () ) dataSet.end ();
	}
}
 
Example #25
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 #26
Source File: RdfDataManager.java    From rdf2neo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Uses the underlining TDB and mapping queries to create a new {@link CyNode} instance.
 * 
 * @param nodeRes the RDF/Jena resource correspnding to the Cypher node. This provides the ?iri paramter in the queries below.
 * @param labelsSparql the node labels query, which is usually taken from {@link CyNodeLoadingHandler#getLabelsSparql()}.
 * @param propsSparql the node properties query, which is usually taken from {@link CyNodeLoadingHandler#getNodePropsSparql()}.
 */
public CyNode getCyNode ( Resource nodeRes, String labelsSparql, String propsSparql )
{
	ensureOpen ();
	
	QuerySolutionMap params = new QuerySolutionMap ();
	params.add ( "iri", nodeRes );

	CyNode cyNode = new CyNode ( nodeRes.getURI () );
	
	// The node's labels
	if ( labelsSparql != null )
	{
		// If it's omitted, it will get the default label.
		Query qry = SparqlUtils.getCachedQuery ( labelsSparql );
		Function<String, String> labelIdConverter = this.getCyNodeLabelIdConverter ();
		
		boolean wasInTnx = dataSet.isInTransaction ();
		if ( !wasInTnx ) dataSet.begin ( ReadWrite.READ );
		try {
			QueryExecution qx = QueryExecutionFactory.create ( qry, this.getDataSet(), params );
			qx.execSelect ().forEachRemaining ( row ->
				cyNode.addLabel ( this.getCypherId ( row.get ( "label" ), labelIdConverter ) )
			);
		}
		finally {
			if ( !wasInTnx && dataSet.isInTransaction () ) dataSet.end ();
		}
	}
	
	// and the properties
	this.addCypherProps ( cyNode, propsSparql );
	
	return cyNode;
}
 
Example #27
Source File: TarqlQueryExecution.java    From tarql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private QueryExecution createQueryExecution(Query query, Model model) {
	QueryExecution result = QueryExecutionFactory.create(query, model);
	PrefixMappingImpl prefixes = new PrefixMappingImpl();
	prefixes.setNsPrefixes(tq.getPrologue().getPrefixMapping());
	prefixes.setNsPrefix("tarql", tarql.NS);
	result.getContext().set(ExpandPrefixFunction.PREFIX_MAPPING, prefixes);
	return result;
}
 
Example #28
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 #29
Source File: Utils.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 *   Device정보 리턴
 * @param deviceUri
 * @return String
 * @throws Exception
 */
public static String getDeviceInfo(String deviceUri) throws Exception {
	String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.dw.sparql.endpoint")+"/sparql";
	StringWriter out = new StringWriter();
	String query = getSparQlHeader() + "\n"+ "describe "+ deviceUri;

	QueryExecution qe = QueryExecutionFactory.sparqlService(serviceURI, query);
	Model model =   qe.execDescribe();
	qe.close();
	model.write(out,"RDF/XML");
	return out.toString();
}
 
Example #30
Source File: Utils.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static final void getTripleAll() throws Exception {
	String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.sparql.endpoint");

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

	ResultSet rs = queryExec.execSelect();
	ResultSetFormatter.out(rs);
}