com.hp.hpl.jena.query.Query Java Examples

The following examples show how to use com.hp.hpl.jena.query.Query. 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: SPARQLExample.java    From GeoTriples with Apache License 2.0 7 votes vote down vote up
public static void main(String[] args) {
	ModelD2RQ m = new ModelD2RQ("file:doc/example/mapping-iswc.ttl");
	String sparql = 
		"PREFIX dc: <http://purl.org/dc/elements/1.1/>" +
		"PREFIX foaf: <http://xmlns.com/foaf/0.1/>" +
		"SELECT ?paperTitle ?authorName WHERE {" +
		"    ?paper dc:title ?paperTitle . " +
		"    ?paper dc:creator ?author ." +
		"    ?author foaf:name ?authorName ." +
		"}";
	Query q = QueryFactory.create(sparql); 
	ResultSet rs = QueryExecutionFactory.create(q, m).execSelect();
	while (rs.hasNext()) {
		QuerySolution row = rs.nextSolution();
		System.out.println("Title: " + row.getLiteral("paperTitle").getString());
		System.out.println("Author: " + row.getLiteral("authorName").getString());
	}
	m.close();
}
 
Example #2
Source File: ResponseContentTypeChoiceTestCase.java    From SolRDF with Apache License 2.0 6 votes vote down vote up
/**
 * Set up fixture for this test case.
 */
@Before
public void setUp() {
	cut = new HybridResponseWriter();
	request = mock(SolrQueryRequest.class);
	response = mock(SolrQueryResponse.class);
	httpRequest = mock(HttpServletRequest.class);
	requestContext = new HashMap<Object, Object>();
	requestContext.put(Names.HTTP_REQUEST_KEY, httpRequest);
	when(request.getContext()).thenReturn(requestContext);

	final NamedList<Object> configuration = new NamedList<Object>();
	final NamedList<Object> contentTypeConfiguration = new NamedList<Object>();
	contentTypeConfiguration
			.add(String.valueOf(Query.QueryTypeSelect),
					"application/sparql-results+xml,application/sparql-results+json,text/csv,text/plain,text/tab-separated-values");
	contentTypeConfiguration.add(String.valueOf(Query.QueryTypeConstruct),
			"application/rdf+xml,application/n-triples,text/turtle");
	contentTypeConfiguration.add(String.valueOf(Query.QueryTypeDescribe),
			"application/rdf+xml,application/n-triples,text/turtle");
	contentTypeConfiguration
			.add(String.valueOf(Query.QueryTypeAsk),
					"text/csv,text/plain,text/tab-separated-values,application/sparql-results+xml,application/sparql-results+json");
	configuration.add("content-types", contentTypeConfiguration);
	cut.init(configuration);
}
 
Example #3
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 #4
Source File: ModelSetImplJena.java    From semweb4j with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public ClosableIterable<Statement> sparqlConstruct(String query)
		throws ModelRuntimeException, MalformedQueryException {
	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> 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 #6
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 #7
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 #8
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 #9
Source File: HybridResponseWriter.java    From SolRDF with Apache License 2.0 6 votes vote down vote up
/**
 * Determines the content type that will be associated with this response writer.
 * 
 * @param request the current Solr request.
 * @return the content type associated with this response writer.
 */
String getContentType(final SolrQueryRequest request, final boolean log) {
	final Query query = (Query)request.getContext().get(Names.QUERY);
	if (query == null) {
		return null;
	}

	final HttpServletRequest httpRequest = (HttpServletRequest) request.getContext().get(Names.HTTP_REQUEST_KEY);
	final String accept = httpRequest.getHeader(HttpHeaders.ACCEPT);
	
	final String [] mediaTypes = accept != null ? accept.split(",") : null;
	String [] requestedMediaTypes = null;
	if (mediaTypes != null) {
		requestedMediaTypes = new String[mediaTypes.length];
		for (int i = 0; i < mediaTypes.length; i++) {
			requestedMediaTypes[i] = cleanMediaType(mediaTypes[i]);
		}
	}
	
	final String contentType = contentTypeChoiceStrategies.get(query.getQueryType()).getContentType(requestedMediaTypes);

	if (log) {
		LOGGER.debug(MessageCatalog._00092_NEGOTIATED_CONTENT_TYPE, query.getQueryType(), accept, contentType);
	}
	return contentType;
}
 
Example #10
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 #11
Source File: ResponseContentTypeChoiceTestCase.java    From SolRDF with Apache License 2.0 6 votes vote down vote up
/**
 * Internal method used for asserting the behaviour of the system in case
 * the incoming request doesn't contain a valid media type.
 * 
 * @param query the query, which can be one of Ask, Select, Construct, Describe.
 * @param mediaTypes the media types that are supposed to be supported.
 */
private void assertIncomingRequestWithoutMediaType(final Query query) {
	requestContext.put(Names.QUERY, query);
	when(httpRequest.getHeader(HttpHeaders.ACCEPT)).thenReturn(null);
	String contentType = cut.getContentType(request, false);
	assertNotNull(contentType);
	assertEquals(
			cut.contentTypeChoiceStrategies.get(query.getQueryType()).getContentType(null), 
			contentType);

	contentType = cut.getContentType(request, false);
	assertNotNull(contentType);
	assertEquals(
			cut.contentTypeChoiceStrategies.get(query.getQueryType()).getContentType(null), 
			contentType);
}
 
Example #12
Source File: ResponseContentTypeChoiceTestCase.java    From SolRDF with Apache License 2.0 6 votes vote down vote up
/**
 * Internal method used for asserting the behaviour of the system in case
 * the incoming request contains an invalid media type.
 * 
 * @param query the query, which can be one of Ask, Select, Construct, Describe.
 * @param mediaTypes the media types that are supposed to be supported.
 */
private void assertIncomingRequestWithInvalidMediaType(final Query query) {
	requestContext.put(Names.QUERY, query);

	final String invalidMediaType = randomString();
	when(httpRequest.getHeader(HttpHeaders.ACCEPT)).thenReturn(invalidMediaType);

	String contentType = cut.getContentType(request, false);
	assertNotNull(contentType);
	assertEquals(
			cut.contentTypeChoiceStrategies.get(query.getQueryType()).getContentType(
					new String[] { invalidMediaType }), 
			contentType);

	contentType = cut.getContentType(request, response);
	assertNotNull(contentType);
	assertEquals(
			cut.contentTypeChoiceStrategies.get(query.getQueryType()).getContentType(
					new String[] { invalidMediaType }), 
			contentType);
}
 
Example #13
Source File: DBPediaCandidateType.java    From uncc2014watsonsim with GNU General Public License v2.0 6 votes vote down vote up
private Query getQuery(String text) {
	ParameterizedSparqlString sparql = new ParameterizedSparqlString(
			"PREFIX : <http://dbpedia.org/resource/>\n"
			+ "PREFIX dbo: <http://dbpedia.org/ontology/>\n"
			+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
			+ "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"
			+ "select distinct ?kind where {\n"
			+ "{?content dbo:wikiPageDisambiguates ?article."
			+ " ?article a ?kind_resource.}"
			+ "Union"
			+ "{?content a ?kind_resource.}"
			+ "?kind_resource rdfs:label ?kind."
			+ "FILTER ("
				+ "langMatches(lang(?kind), 'EN')"
			+ ")} limit 10");
	List<String> uris = rdf_label_search.query(text);
	if (uris.size() > 0) sparql.setIri("content", uris.get(0));
	else sparql.setIri("content", "uri:moo:ajklhawkjd");
	return sparql.asQuery();
	
}
 
Example #14
Source File: Course_Test.java    From neo4jena with Apache License 2.0 6 votes vote down vote up
public static void getJob(GraphDatabaseService njgraph)
{
	NeoGraph graph = new NeoGraph(njgraph);
	Model njmodel = ModelFactory.createModelForGraph(graph);
	
	ST descJob = TemplateLoader.getQueriesGroup().getInstanceOf("getGraph");
	String queryASString = Constants.QUERY_PREFIX+ descJob.render();
	
	Query query = QueryFactory.create(queryASString, Syntax.syntaxSPARQL_11);
	QueryExecution qexec = QueryExecutionFactory.create(query, njmodel);
	ResultSet res = qexec.execSelect();
	
	int count=0;
       while(res.hasNext()){
       	//System.out.println("in while"+count);
       	QuerySolution sol = res.next();
       	System.out.println(sol.get("?Z"));
       	count++;
       }
      
      //log.info("Record fetched:"+ count);
      System.out.println("Record fetched:"+ count);
}
 
Example #15
Source File: HybridResponseWriter.java    From SolRDF with Apache License 2.0 5 votes vote down vote up
@Override
public void write(
		final Writer writer, 
		final SolrQueryRequest request, 
		final SolrQueryResponse response) throws IOException {		
	final NamedList<?> values = response.getValues();
	final Query query = (Query)request.getContext().get(Names.QUERY);
	final QueryExecution execution = (QueryExecution)response.getValues().get(Names.QUERY_EXECUTION);
	try {
		final boolean isHybridMode = Boolean.TRUE.equals(request.getContext().get(Names.HYBRID_MODE));
		if (isHybridMode) {
			response.add(Names.SOLR_REQUEST, request);
			response.add(Names.SOLR_RESPONSE, response);
			
			final String contentType = contentTypeRewrites.get(getContentType(request, false));
			WriterStrategy strategy = compositeWriters.get(contentType);
			strategy = strategy != null ? strategy : compositeWriters.get("text/xml");
			strategy.doWrite(values, writer, contentType);
		} else {
			if (query == null || execution == null) {
				LOGGER.error(MessageCatalog._00091_NULL_QUERY_OR_EXECUTION);
				return;
			}
			writers.get(query.getQueryType()).doWrite(values, writer, getContentType(request, false));
		}
	} finally {
		if (execution != null) {
			// CHECKSTYLE:OFF
			try { execution.close();} catch (final Exception ignore) {}
			// CHECKSTYLE:ON
		}			
	}			
}
 
Example #16
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 #17
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 #18
Source File: HybridXMLWriter.java    From SolRDF with Apache License 2.0 5 votes vote down vote up
/**
 * Writes out a given name / value pair. 
 * This is similar to {@link XMLWriter#writeVal(String, Object)}. 
 * This is needed because that similar method is not extensible and cannot be overriden 
 * (it is called recursively by other methods).
 * 
 * @param name the name of the attribute.
 * @param value the value of the attribute.
 * @param data the complete set of response values.
 * @throws IOException in case of I/O failure.
 */
public void writeValue(final String name, final Object value, final NamedList<?> data) throws IOException {
	if (value == null) {
		writeNull(name);	
	} else if (value instanceof ResultSet) {
		final int start = req.getParams().getInt(CommonParams.START, 0);
		final int rows = req.getParams().getInt(CommonParams.ROWS, 10);
		writeStartDocumentList("response", start, rows, (Integer) data.remove(Names.NUM_FOUND), 1.0f);
		final XMLOutput outputter = new XMLOutput(false);
		outputter.format(new WriterOutputStream(writer), (ResultSet)value);
		writeEndDocumentList();
	} else if (value instanceof String || value instanceof Query) {
		writeStr(name, value.toString(), false);
	} else if (value instanceof Number) {
		if (value instanceof Integer || value instanceof Short || value instanceof Byte) {
			writeInt(name, value.toString());
		} else if (value instanceof Long) {
			writeLong(name, value.toString());
		} else if (value instanceof Float) {
			writeFloat(name, ((Float) value).floatValue());
		} else if (value instanceof Double) {
			writeDouble(name, ((Double) value).doubleValue());
		} 
	} else if (value instanceof Boolean) {
		writeBool(name, value.toString());
	} else if (value instanceof Date) {
		writeDate(name, (Date) value);
	} else if (value instanceof Map) {
		writeMap(name, (Map<?,?>) value, false, true);
	} else if (value instanceof NamedList) {
		writeNamedList(name, (NamedList<?>) value);
	} else if (value instanceof Iterable) {
		writeArray(name, ((Iterable<?>) value).iterator());
	} else if (value instanceof Object[]) {
		writeArray(name, (Object[]) value);
	} else if (value instanceof Iterator) {
		writeArray(name, (Iterator<?>) value);
	} 
}
 
Example #19
Source File: Sparql.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
private static String queryTypeToString(int qtype)
{
   switch (qtype)
   {
      case Query.QueryTypeAsk:       return "ASK";
      case Query.QueryTypeConstruct: return "CONSTRUCT";
      case Query.QueryTypeDescribe:  return "DESCRIBE";
      case Query.QueryTypeSelect:    return "SELECT";
      case Query.QueryTypeUnknown:
      default:
         return "unknown";
   }
}
 
Example #20
Source File: ResponseContentTypeChoiceTestCase.java    From SolRDF with Apache License 2.0 5 votes vote down vote up
/**
 * Internal method used for asserting the behaviour of the system in case
 * the incoming request contains a valid media type.
 * 
 * @param query the query, which can be one of Ask, Select, Construct, Describe.
 * @param mediaTypes the media types that are supposed to be supported.
 */
private void assertIncomingRequestWithMediaType(final Query query, final String[] mediaTypes) {
	requestContext.put(Names.QUERY, query);

	for (final String mediaType : mediaTypes) {
		assertSupportedMediaType(mediaType);
		assertSupportedMediaType(mediaType + ";q=0.2;charset=utf8;level=2");
	}
}
 
Example #21
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 #22
Source File: SparqlExtractorUI.java    From wandora with GNU General Public License v3.0 5 votes vote down vote up
public void checkSPARQLQuery(String query) {
    try {
        Query q = QueryFactory.create(query);
        WandoraOptionPane.showMessageDialog(wandora, "SPARQL query successfully checked. Syntax OK.", "Syntax OK");
    }
    catch(Exception e) {
        WandoraOptionPane.showMessageDialog(wandora, "Syntax Error: "+e.getMessage(), "Syntax Error");
        //wandora.handleError(e);
    }
}
 
Example #23
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 #24
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 #25
Source File: UnionSelectorEvaluator.java    From anno4j with Apache License 2.0 5 votes vote down vote up
@Override
public Var evaluate(NodeSelector nodeSelector, ElementGroup elementGroup, Var var, LDPathEvaluatorConfiguration evaluatorConfiguration) {
    UnionSelector unionSelector = (UnionSelector) nodeSelector;

    NodeSelector nodeSelectorLeft = unionSelector.getLeft();
    NodeSelector nodeSelectorRight = unionSelector.getRight();

    ElementGroup leftGroup = new ElementGroup();
    ElementGroup rightGroup = new ElementGroup();

    Var leftVar = LDPathEvaluator.evaluate(nodeSelectorLeft, leftGroup, var, evaluatorConfiguration);
    Var rightVar = LDPathEvaluator.evaluate(nodeSelectorRight, rightGroup, var, evaluatorConfiguration);

    Var subVar = Var.alloc(VarIDGenerator.createID());

    Query leftSubQuery = new Query();
    leftGroup.addElement(new ElementBind(subVar, new NodeValueNode(leftVar.asNode())));
    leftSubQuery.setQueryPattern(leftGroup);
    leftSubQuery.addResultVar(var);
    leftSubQuery.addResultVar(subVar);
    leftSubQuery.setQuerySelectType();
    ElementSubQuery leftESubQuery = new ElementSubQuery(leftSubQuery);

    Query rightSubQuery = new Query();
    rightGroup.addElement(new ElementBind(subVar, new NodeValueNode(rightVar.asNode())));
    rightSubQuery.setQueryPattern(rightGroup);
    rightSubQuery.addResultVar(var);
    rightSubQuery.addResultVar(subVar);
    rightSubQuery.setQuerySelectType();
    ElementSubQuery rightESubQuery = new ElementSubQuery(rightSubQuery);


    ElementUnion elementUnion = new ElementUnion();

    elementUnion.addElement(leftESubQuery);
    elementUnion.addElement(rightESubQuery);
    elementGroup.addElement(elementUnion);

    return subVar;
}
 
Example #26
Source File: EvalQuery.java    From anno4j with Apache License 2.0 5 votes vote down vote up
public static <T extends ResourceObject> Query evaluate(QueryServiceConfiguration queryServiceDTO, URI rootType) throws ParseException {

        Query query = QueryFactory.make();
        query.setQuerySelectType();

        ElementGroup elementGroup = new ElementGroup();

        Var objectVar = Var.alloc("root");

        // Creating and adding the first triple - could be something like: "?objectVar rdf:type oa:Annotation
        Triple t1 = new Triple(objectVar, RDF.type.asNode(), NodeFactory.createURI(rootType.toString()));
        elementGroup.addTriplePattern(t1);

        // Evaluating the criteria
        for (Criteria c : queryServiceDTO.getCriteria()) {
            SesameValueBackend backend = new SesameValueBackend();

            LdPathParser parser = new LdPathParser(backend, queryServiceDTO.getConfiguration(), new StringReader(c.getLdpath()));
            Var var = LDPathEvaluator.evaluate(parser.parseSelector(queryServiceDTO.getPrefixes()), elementGroup, objectVar, queryServiceDTO.getEvaluatorConfiguration());

            if (c.getConstraint() != null) {
                String resolvedConstraint = resolveConstraintPrefix(c.getConstraint(), queryServiceDTO, parser);
                EvalComparison.evaluate(elementGroup, c, var, resolvedConstraint);
            }
        }

        // Adding all generated patterns to the query object
        query.setQueryPattern(elementGroup);

        // Choose what we want so select - SELECT ?annotation in this case
        query.addResultVar(objectVar);

        // Setting the default prefixes, like rdf: or dc:
        query.getPrefixMapping().setNsPrefixes(queryServiceDTO.getPrefixes());

        return query;
    }
 
Example #27
Source File: QueryResultTableImpl.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public QueryResultTableImpl(Query query, Model jenaModel) throws ModelRuntimeException {
	
	if(!query.isSelectType()) {
		throw new ModelRuntimeException("The given query is not a SELECT query");
	}
	// else
	this.varnames = new ArrayList<String>();
	for(Object o : query.getResultVars()) {
		this.varnames.add((String)o);
	}
	this.qexec = QueryExecutionFactory.create(query, jenaModel);
}
 
Example #28
Source File: QueryResultTableImpl.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public QueryResultTableImpl(Query query, Dataset jenaDataset) throws ModelRuntimeException {
	
	if(!query.isSelectType()) {
		throw new ModelRuntimeException("The given query is not a SELECT query");
	}
	// else
	this.varnames = new ArrayList<String>();
	for(Object o : query.getResultVars()) {
		this.varnames.add((String)o);
	}
	this.qexec = QueryExecutionFactory.create(query, jenaDataset);
}
 
Example #29
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 #30
Source File: ModelImplJena.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public boolean sparqlAsk(String queryString) throws ModelRuntimeException {
	assertModel();
	log.debug("Query " + queryString);
	Query query = QueryFactory.create(queryString);
	
	if(!query.isAskType()) {
		throw new ModelRuntimeException("The given query is not an ASK query");
	}
	// else
	QueryExecution qexec = QueryExecutionFactory.create(query, this.jenaModel);
	return qexec.execAsk();
}