Java Code Examples for com.hp.hpl.jena.query.QueryFactory#create()

The following examples show how to use com.hp.hpl.jena.query.QueryFactory#create() . 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: FromAndFromNamedClauses_ITCase.java    From SolRDF with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	Dataset memoryDataset = DatasetFactory.createMem();
	Model memoryModel = ModelFactory.createDefaultModel();
	memoryModel.read(new FileReader("/work/workspaces/rdf/SolRDF/solrdf/src/test/resources/sample_data/one_triple_1.ttl"), "http://e.org", "TTL");
	memoryDataset.addNamedModel("http://grapha.com", memoryModel);
	
	memoryModel = ModelFactory.createDefaultModel();
	memoryModel.read(new FileReader("/work/workspaces/rdf/SolRDF/solrdf/src/test/resources/sample_data/one_triple_2.ttl"), "http://e.org", "TTL");
	memoryDataset.addNamedModel("http://graphb.com", memoryModel);
	
	memoryModel = ModelFactory.createDefaultModel();
	memoryModel.read(new FileReader("/work/workspaces/rdf/SolRDF/solrdf/src/test/resources/sample_data/one_triple_3.ttl"), "http://e.org", "TTL");
	memoryDataset.addNamedModel("http://graphc.com", memoryModel);
	
	memoryModel = ModelFactory.createDefaultModel();
	memoryModel.read(new FileReader("/work/workspaces/rdf/SolRDF/solrdf/src/test/resources/sample_data/one_triple_4.ttl"), "http://e.org", "TTL");
	memoryDataset.addNamedModel("http://graphd.com", memoryModel);
	
	final Query query = QueryFactory.create(q2());//"SELECT ?s FROM <http://grapha.com> WHERE { ?s <http://example.org/title> ?o }");
	
	System.out.println(ResultSetFormatter.asText(QueryExecutionFactory.create(query, memoryDataset).execSelect()));
}
 
Example 2
Source File: ModelImplJena.java    From semweb4j with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public ClosableIterable<Statement> sparqlConstruct(String queryString)
        throws ModelRuntimeException {
	assertModel();
	Query query = QueryFactory.create(queryString);
	QueryExecution qexec = QueryExecutionFactory.create(query, this.jenaModel);
	
	if(query.isConstructType()) {
		com.hp.hpl.jena.rdf.model.Model m = qexec.execConstruct();
		Model resultModel = new ModelImplJena(null, m, Reasoning.none);
		resultModel.open();
		return resultModel;
	} else {
		throw new RuntimeException("Cannot handle this type of queries! Please use CONSTRUCT.");
	}
}
 
Example 3
Source File: ModelImplJena.java    From semweb4j with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * @return opened result Model
 */
@Override
public ClosableIterable<Statement> sparqlDescribe(String queryString)
        throws ModelRuntimeException {
	assertModel();
	Query query = QueryFactory.create(queryString);
	QueryExecution qexec = QueryExecutionFactory.create(query, this.jenaModel);
	
	if(query.isDescribeType()) {
		com.hp.hpl.jena.rdf.model.Model m = qexec.execDescribe();
		Model resultModel = new ModelImplJena(null, m, Reasoning.none);
		resultModel.open();
		return resultModel;
	} else {
		throw new RuntimeException("Cannot handle this type of queries! Please use DESCRIBE.");
	}
	
}
 
Example 4
Source File: ModelSetImplJena.java    From semweb4j with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public ClosableIterable<Statement> queryConstruct(String query,
		String querylanguage) throws QueryLanguageNotSupportedException,
		MalformedQueryException, ModelRuntimeException {

	Query jenaQuery = QueryFactory.create(query);
	QueryExecution qexec = QueryExecutionFactory.create(jenaQuery,
			this.dataset);

	if (jenaQuery.isConstructType()) {
		com.hp.hpl.jena.rdf.model.Model m = qexec.execConstruct();
		Model resultModel = new ModelImplJena(null, m, Reasoning.none);
		resultModel.open();
		return resultModel;
	} else {
		throw new RuntimeException(
				"Cannot handle this type of query! Please use CONSTRUCT.");
	}
}
 
Example 5
Source File: ModelSetImplJena.java    From semweb4j with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public ClosableIterable<Statement> sparqlDescribe(String query)
		throws ModelRuntimeException {
	Query jenaQuery = QueryFactory.create(query);
	QueryExecution qexec = QueryExecutionFactory.create(jenaQuery,
			this.dataset);

	if (jenaQuery.isDescribeType()) {
		com.hp.hpl.jena.rdf.model.Model m = qexec.execDescribe();
		Model resultModel = new ModelImplJena(null, m, Reasoning.none);
		resultModel.open();
		return resultModel;
	} else {
		throw new RuntimeException(
				"Cannot handle this type of query! Please use DESCRIBE.");
	}
}
 
Example 6
Source File: AliadaRDFStoreDAO.java    From aliada-tool with GNU General Public License v3.0 6 votes vote down vote up
public String crm2AliadaClass(final String crmClass) {
	final Query query = QueryFactory.create(CRM_TO_ALIADA_CLASS_P1 + crmClass + CRM_TO_ALIADA_CLASS_P2);
	ARQ.getContext().setTrue(ARQ.useSAX);
       
	QueryExecution execution = null;
	try {
		execution = QueryExecutionFactory.sparqlService("http://172.25.5.15:8890/sparql", query);
		execution.setTimeout(2000, 5000);
		final ResultSet results = execution.execSelect();
		//Iterating over the SPARQL Query results
		while (results.hasNext()) {
			QuerySolution soln = results.nextSolution();
			//Printing DBpedia entries' abstract.
			System.out.println(soln.get("?abstract"));   
			return soln.get("?abstract").asResource().getURI();
		}
		return "NULL";
       } finally {
       	try {
       		execution.close();
		} catch (Exception exception) {
			// TODO: handle exception
		}
       }

}
 
Example 7
Source File: ModelSetImplJena.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public QueryResultTable sparqlSelect(String queryString)
		throws MalformedQueryException, ModelRuntimeException {
	Query jenaQuery = QueryFactory.create(queryString);
	return new QueryResultTableImpl(jenaQuery,
			this.dataset);
}
 
Example 8
Source File: IntegrationTestSupertypeLayer.java    From SolRDF with Apache License 2.0 5 votes vote down vote up
/**
 * Executes a given CONSTRUCT query against a given dataset.
 * 
 * @param data the mistery guest containing test data (query and dataset)
 * @throws Exception never, otherwise the test fails.
 */
protected void describeTest(final MisteryGuest data) throws Exception {
	load(data);
	
	final Query query = QueryFactory.create(queryString(data.query));
	try {
		inMemoryExecution = QueryExecutionFactory.create(query, memoryDataset);
		
		assertTrue(
				Arrays.toString(data.datasets) + ", " + data.query,
				inMemoryExecution.execDescribe().isIsomorphicWith(
						SOLRDF_CLIENT.describe(queryString(data.query))));
	} catch (final Throwable error) {
		StringWriter writer = new StringWriter();
		RDFDataMgr.write(writer, SOLRDF_CLIENT.describe(queryString(data.query)), RDFFormat.NTRIPLES);
		log.debug("JNS\n" + writer);
		
		QueryExecution debugExecution = QueryExecutionFactory.create(query, memoryDataset);
		writer = new StringWriter();
		RDFDataMgr.write(writer, debugExecution.execDescribe(), RDFFormat.NTRIPLES);
		
		log.debug("MEM\n" + writer);
		
		debugExecution.close();
		throw error;
	} 
}
 
Example 9
Source File: Course.java    From neo4jena with Apache License 2.0 5 votes vote down vote up
public static void search(GraphDatabaseService njgraph) {
	NeoGraph graph = new NeoGraph(njgraph);
	Model njmodel = ModelFactory.createModelForGraph(graph);
	
	String s2 = "prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n" +
               	"PREFIX uni: <http://seecs.edu.pk/db885#>" +
               	"PREFIX foaf: <http://xmlns.com/foaf/0.1/> " +
               "SELECT ?X ?Z ?Y "+
               "WHERE" +
               "{ ?X ?Z ?Y ." +
               "}"; 
      	          
       Query query = QueryFactory.create(s2); 
       QueryExecution qExe = QueryExecutionFactory.create(query, njmodel);
       StopWatch watch = new StopWatch();
       ResultSet results = qExe.execSelect();
       log.info("Query took (ms): "+ watch.stop());
       System.out.println("Query took (ms): "+ watch.stop());
      // ResultSetFormatter.out(System.out, results);
       
       int count=0;
       while(results.hasNext()){
       	//System.out.println("in while"+count);
       	QuerySolution sol = results.next();
       	System.out.println(sol.get("?Z"));
       	count++;
       }
      
      log.info("Record fetched:"+ count);
      System.out.println("Record fetched:"+ count);
}
 
Example 10
Source File: Wine.java    From neo4jena with Apache License 2.0 5 votes vote down vote up
public static void search(GraphDatabaseService njgraph) {
	NeoGraph graph = new NeoGraph(njgraph);
	Model njmodel = ModelFactory.createModelForGraph(graph);
	      
	String s2 = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>" +
				"PREFIX food: <http://www.w3.org/TR/2003/PR-owl-guide-20031209/food#>"+
				"PREFIX wine: <http://www.w3.org/TR/2003/PR-owl-guide-20031209/wine#>" +
				"PREFIX owl: <http://www.w3.org/2002/07/owl#>"+
				"SELECT ?X WHERE {"+
				"?X food:SweetFruit ?Z . }";

       Query query = QueryFactory.create(s2);
       QueryExecution qExe = QueryExecutionFactory.create(query, njmodel);
       StopWatch watch = new StopWatch();
       ResultSet results = qExe.execSelect();
       System.out.println("Query took (ms): "+ watch.stop());
       //ResultSetFormatter.out(System.out, results);
       
       int count=0;
       while(results.hasNext()){
       	//System.out.println("in while"+count);
       	QuerySolution sol = results.next();
       	System.out.print(sol.get("X"));
       	count++;
       }
      System.out.println("Record fetched:"+ count);
      
}
 
Example 11
Source File: Course_Test.java    From neo4jena with Apache License 2.0 5 votes vote down vote up
public static void search(GraphDatabaseService njgraph) {
	NeoGraph graph = new NeoGraph(njgraph);
	Model njmodel = ModelFactory.createModelForGraph(graph);
	
	String s2 = "prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n" +
               	"PREFIX uni: <http://seecs.edu.pk/db885#>" +
               	"PREFIX foaf: <http://xmlns.com/foaf/0.1/> " +
               "SELECT ?X ?Z ?Y "+
               "WHERE" +
               "{ ?X ?Z ?Y ." +
               "}"; 
      	          
       Query query = QueryFactory.create(s2); 
       QueryExecution qExe = QueryExecutionFactory.create(query, njmodel);
       StopWatch watch = new StopWatch();
       ResultSet results = qExe.execSelect();
       long endTime = watch.stop();
       log.info("Query took (ms): "+endTime);
       System.out.println("Query took (ms): "+ endTime);
      // ResultSetFormatter.out(System.out, results);
       
       int count=0;
       while(results.hasNext()){
       	//System.out.println("in while"+count);
       	QuerySolution sol = results.next();
       	System.out.println(sol.get("?Z"));
       	count++;
       }
      
      log.info("Record fetched:"+ count);
      System.out.println("Record fetched:"+ count);
}
 
Example 12
Source File: QueryHelper.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
private Query build() {
	String resolvedQuery=this.rawQuery;
	for(Entry<String,String> entry:this.params.entrySet()) {
		resolvedQuery=
			TestingUtil.
				interpolate(
					resolvedQuery,
					entry.getKey(),
					entry.getValue());
	}
	return QueryFactory.create(resolvedQuery);
}
 
Example 13
Source File: ModelSetImplJena.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public QueryResultTable querySelect(String query, String querylanguage)
		throws QueryLanguageNotSupportedException, MalformedQueryException,
		ModelRuntimeException {
	com.hp.hpl.jena.query.Syntax syntax = com.hp.hpl.jena.query.Syntax
			.lookup(querylanguage);
	if (syntax == null) {
		// delegate to super
		throw new QueryLanguageNotSupportedException(
				"Unsupported query language: " + querylanguage);
	}
	Query jenaQuery = QueryFactory.create(query, syntax);
	return new QueryResultTableImpl(jenaQuery,
			this.dataset);
}
 
Example 14
Source File: TestingUtilTest.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testInterpolate() throws Exception {
	String baseQuery=
		TestingUtil.
			loadResource("queries/service_builds.sparql");

	String rawQuery=
		TestingUtil.
			interpolate(
				baseQuery,
				"service",
				"<http://www.example.org/service/>");

	QueryFactory.create(rawQuery);
}
 
Example 15
Source File: ModelImplJena.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public QueryResultTable sparqlSelect(String queryString) throws ModelRuntimeException {
	assertModel();
	log.debug("Query " + queryString);
	Query query = QueryFactory.create(queryString);
	return new QueryResultTableImpl(query, this.jenaModel);
}
 
Example 16
Source File: SPARQLService.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Runs SPARQL queries
 * 
 * @param type
 *            Result Format: N3, N-TRIPLE, RDF/XML, RDF/XML-ABBREV, TURTLE
 * @param query
 *            Sparql for the query
 * @return
 */
@GET
@Produces({ WebUtil.MEDIA_TYPE_APPLICATION_NTRIPLE,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFJSON,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFXML, MediaType.TEXT_PLAIN,
		WebUtil.MEDIA_TYPE_TEXT_N3, WebUtil.MEDIA_TYPE_TEXT_TURTLE })
public Response selectQuery(@QueryParam("sparql") String query,
		@Context Request request) {

	Variant variant = request.selectVariant(WebUtil.VARIANTS);
	MediaType mediaType = variant.getMediaType();

	Repository repository = RepositoryManager.getInstance().getRepository();
	OntModel ontModel = repository.getMDRDatabase().getOntModel();
	Query q = null;

	try {
		query = URLDecoder.decode(query, "UTF-8");
		q = QueryFactory.create(query);
	} catch (Exception exc) {
		logger.error("Error during the creation of the SPARQL query", exc);
		return Response.serverError().build();
	}

	QueryExecution qexec = QueryExecutionFactory.create(q, ontModel);
	Model resultModel = null;
	if (q.isSelectType()) {
		ResultSet resultSet = qexec.execSelect();
		resultModel = ResultSetFormatter.toModel(resultSet);
	} else {
		throw new WebApplicationException(Status.UNAUTHORIZED);
	}
	qexec.close();

	graphStream.setModel(resultModel);
	graphStream.setLanguage(WebUtil.getSerializationLanguage(mediaType
			.toString()));

	return Response.ok(graphStream).build();
}
 
Example 17
Source File: SerializationService.java    From semanticMDR with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 
 * @param type
 *            outputFormat "N3", "N-TRIPLE", "RDF/XML-ABBREV" or
 *            "TURTLE"default: "RDF/XML".
 * @param uuid
 * @return
 */
@GET
@Path("/graph")
@Produces({ WebUtil.MEDIA_TYPE_APPLICATION_NTRIPLE,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFJSON,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFXML, MediaType.TEXT_PLAIN,
		WebUtil.MEDIA_TYPE_TEXT_N3, WebUtil.MEDIA_TYPE_TEXT_TURTLE })
public Response serialize(@QueryParam("id") String uuid, @QueryParam("uri") String uri,
		@Context Request request) {

	Variant variant = request.selectVariant(WebUtil.VARIANTS);
	MediaType mediaType = variant.getMediaType();

	Repository repository = RepositoryManager.getInstance().getRepository();
	OntModel ontModel = repository.getMDRDatabase().getOntModel();
	
	String query = "";
	if(uuid != null) {
		// get the uri of the resource
		query = "prefix mdr:     <http://www.salusproject.eu/iso11179-3/mdr#> "
				+ "prefix xsd:     <http://www.w3.org/2001/XMLSchema#> "
				+ "SELECT ?resource WHERE { " + "?resource ?op ?ar . "
				+ "?ar mdr:administeredItemIdentifier ?ii . "
				+ "?ii mdr:dataIdentifier \"" + uuid + "\"^^xsd:string. " + "}";

		logger.debug("Query execution: {}", query);
		Query q = QueryFactory.create(query);
		QueryExecution qe = QueryExecutionFactory.create(q, ontModel);
		ResultSet rs = qe.execSelect();

		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			uri = qs.getResource("resource").getURI();
		}
	}

	if(uri == null) {
		throw new WebApplicationException(Response.Status.BAD_REQUEST);
	}
	
	// use the uri to construct the model and return its serialization.
	query = "CONSTRUCT WHERE { <" + uri + "> ?p ?o .}";
	Query q2 = QueryFactory.create(query);
	QueryExecution qe2 = QueryExecutionFactory.create(q2, ontModel);
	Model outModel = qe2.execConstruct();

	graphStream.setModel(outModel);
	graphStream.setLanguage(WebUtil.getSerializationLanguage(mediaType
			.toString()));

	return Response.ok(graphStream).build();
}
 
Example 18
Source File: Relation.java    From xcurator with Apache License 2.0 4 votes vote down vote up
private void findAndAddLinkedResouces(Model model,
        Element item, Document dataDoc, Resource parentResouce, String typePrefix) throws XPathExpressionException {

//TODO: Fix it!
    //    createSPARQL();
    // name="x.y.z.y"
    // x
    // ?x y ?y .
    // ?y z ?z .
    // ?z y ?y .
    String whereClause = "WHERE {\n";
    int j = 0;
    whereClause += "?x0 rdf:type <" + getTargetEntity() + "> . \n";

    for (Property lookupProperty : foreignLookupKey.getProperties()) {
        String localValue = XMLUtils.getStringByPath(lookupProperty.getPath(), item, dataDoc).trim();

        if (localValue.length() == 0) {
            continue;
        }
        //      localValue = localValue.replaceAll("\\s+", "\\\\\\\\s+");
        localValue = JenaUtils.querify(localValue);

        String[] splittedRelation = lookupProperty.getElement().getAttribute("name")
                .replace(typePrefix, "")
                .split("\\.");

        int i;
        for (i = 1; i < splittedRelation.length; i++) {
            whereClause += "?x" + (i - 1) + "" + (i != 1 ? j : "") + " t:" + splittedRelation[i] + " ?x" + (i) + "" + j + ".\n";
        }

        whereClause += "FILTER (?x" + (i - 1) + (i != 1 ? j : "") + " = \"" + localValue + "\").\n";

        j++;
    }

    whereClause += "} ";

    String queryStr
            = "PREFIX t: <" + typePrefix + ">\n"
            + "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"
            + "select ?x0 \n" + whereClause;

    LogUtils.debug(this.getClass(), queryStr);

    Query query = QueryFactory.create(queryStr);
    QueryExecution qExec = null;
    try {
        qExec = QueryExecutionFactory.create(query, model);
        ResultSet rs = qExec.execSelect();
        while (rs.hasNext()) {
            QuerySolution solution = rs.next();
            RDFNode subject = solution.get("?x0");
            parentResouce.addProperty(getJenaProperty(model), subject);

        }
    } catch (Exception e) {
        if (debug) {
            e.printStackTrace();
        }
    } finally {
        if (qExec != null) {
            qExec.close();
        }
    }

    //    for (Property lookupProperty: foreignLookupKey.getProperties()) {
    //      String localValue = XMLUtils.getStringByPath(lookupProperty.getPath(), item, dataDoc);
    //      Selector selector = new SimpleSelector(null, lookupProperty.getJenaProperty(model), localValue);
    //      StmtIterator iter = model.listStatements(selector);
    //
    //      while (iter.hasNext()) {
    //        Statement stmt = iter.next();
    //        if (targetEntity.equals(stmt.getSubject().getProperty(RDF.type).getObject().toString())) {
    //          parentResouce.addProperty(getJenaProperty(model), stmt.getSubject());
    //        }
    //      }
    //    }
    //
    //
    //    for (Property lookupProperty: foreignLookupKey.getProperties()) {
    //      String localValue = XMLUtils.getStringByPath(lookupProperty.getPath(), item, dataDoc);
    //      Selector selector = new SimpleSelector(null, lookupProperty.getJenaProperty(model), localValue);
    //      StmtIterator iter = model.listStatements(selector);
    //
    //      while (iter.hasNext()) {
    //        Statement stmt = iter.next();
    //        if (targetEntity.equals(stmt.getSubject().getProperty(RDF.type).getObject().toString())) {
    //          parentResouce.addProperty(getJenaProperty(model), stmt.getSubject());
    //        }
    //      }
    //    }
}
 
Example 19
Source File: Sparql.java    From DataHubSystem with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Object execute(Map<String, EdmLiteral> parameters) throws ODataException
{
   EdmLiteral query_lit = parameters.remove("query");
   // Olingo2 checks for presence of non-nullable parameters for us!
   String query_s = query_lit.getLiteral();
   Query query = QueryFactory.create(query_s);
   if (!(query.isSelectType() || query.isDescribeType()))
   {
      throw new InvalidOperationException(query.getQueryType());
   }

   DrbCortexModel cortexmodel;
   try
   {
      cortexmodel = DrbCortexModel.getDefaultModel();
   }
   catch (IOException ex)
   {
      throw new RuntimeException(ex);
   }

   Model model = cortexmodel.getCortexModel().getOntModel();

   QueryExecution qexec = null;
   // FIXME: QueryExecution in newer versions of Jena (post apache incubation) implement AutoClosable.
   try
   {
      qexec = QueryExecutionFactory.create(query, model);
      if (query.isSelectType())
      {
         ResultSet results = qexec.execSelect();
         return ResultSetFormatter.asXMLString(results);
      }
      else
      {
         Model description = qexec.execDescribe();
         // newer version of Jena have the RIOT package for I/O
         StringWriter strwrt = new StringWriter();
         Abbreviated abb = new Abbreviated();
         abb.write(description, strwrt, null);
         return strwrt.toString();
      }
   }
   finally
   {
      if (qexec != null)
      {
         qexec.close();
      }
   }
}
 
Example 20
Source File: PagedResultSetTestCase.java    From SolRDF with Apache License 2.0 4 votes vote down vote up
/**
 * Executes a "SELECT ALL" query.
 * 
 * @return the {@link ResultSet} as result of the query execution.
 */
ResultSet executeQuery() {
	final Query query = QueryFactory.create("SELECT * WHERE {?s ?p ?o}");
	final QueryExecution execution = QueryExecutionFactory.create(query, model);
	return execution.execSelect();		
}