Java Code Examples for org.apache.jena.query.QueryFactory#create()

The following examples show how to use org.apache.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: TestGeneratorImpl.java    From RDFUnit with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isValid() {
    Query q;
    if (pattern == null) {
        log.error("{} : Pattern {} does not exist", getUri(), getPattern());
        return false;
    }
    try {
        q = QueryFactory.create(PrefixNSService.getSparqlPrefixDecl() + getQuery());
    } catch (Exception e) {
        log.error("{} Cannot parse query:\n{}", getUri(), PrefixNSService.getSparqlPrefixDecl() + getQuery(), e);
        return false;
    }

    Collection<Var> sv = q.getProjectVars();
    if (sv.size() != pattern.getParameters().size() + 1) {
        log.error("{} Select variables are different than Pattern parameters", getUri());
        return false;
    }


    return true;
}
 
Example 2
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 3
Source File: TagRdfUnitTestGenerator.java    From RDFUnit with Apache License 2.0 6 votes vote down vote up
private Set<TestCase> generate(QueryExecutionFactoryModel qef, SchemaSource source, TestGenerator testGenerator) {
    Set<TestCase> tests = new HashSet<>();

    Pattern tgPattern = testGenerator.getPattern();

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

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

        });
    }
    return tests;
}
 
Example 4
Source File: OCUtils.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
public static List<ConjunctiveQuery> loadConjunctiveQueries(File queryFile) throws IOException {
	List<ConjunctiveQuery> ret = new ArrayList<ConjunctiveQuery>();
	Reader in = new FileReader(queryFile);
	for (String queryText: SPARQLFileParser.readQueries(in)) {
		queryText= queryText.trim();
		if (queryText.startsWith("#")) {
			continue;
		}
		Query query= QueryFactory.create(queryText, Syntax.syntaxSPARQL_11);
		if (!query.isSelectType()) {
			logger.debug("Ignoring non select query: {}",query.toString());
			continue;
		}
		logger.debug("Query: {}"+query);
		ret.add(new ConjunctiveQuery(query));
	}
	in.close();
	return ret;
}
 
Example 5
Source File: OCUtils.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
public static List<Query> loadQueries(File queryFile) throws IOException {
	List<Query> ret = new ArrayList<Query>();
	Reader in = new FileReader(queryFile);
	for (String queryText: SPARQLFileParser.readQueries(in)) {
		queryText= queryText.trim();
		if (queryText.startsWith("#")) {
			continue;
		}
		Query query= QueryFactory.create(queryText, Syntax.syntaxSPARQL_11);
		if (!query.isSelectType()) {
			logger.debug("Ignoring non select query: {}",query.toString());
			continue;
		}
		logger.debug("Query: {}"+query);
		ret.add(query);
	}
	in.close();
	return ret;
}
 
Example 6
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 7
Source File: JenaUtil.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
public static Query parse(String queryString) throws MalformedURLException, IOException {
	if (new URL(queryString).openConnection().getInputStream() != null) {
		return QueryFactory.read(queryString);
	} else {
		return QueryFactory.create(queryString);
	}
}
 
Example 8
Source File: ARQTest.java    From tarql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void testSPARQLFilterIsAppliedToValues() {
	Query q = QueryFactory.create(
			"SELECT * { FILTER(?a=1) VALUES (?a) { (1) (2) } }");
	ResultSet rs = QueryExecutionFactory.create(q, 
			ModelFactory.createDefaultModel()).execSelect();
	assertTrue(rs.hasNext());
	assertEquals(binding(vars("a"), "1"), rs.nextBinding());
	assertFalse(rs.hasNext());
}
 
Example 9
Source File: QueryProcessorImpl.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
public static Query compile(OWLQLSPARQLCompiler compiler, String query)
{
org.apache.jena.query.Query jq = QueryFactory.create(query);
org.apache.jena.query.Query compiledJQ = compiler.compile(jq);
logger.debug("QL query compilation:\n\t OriginalQuery: {}\n\t CompiledQuery:\n\t{}", jq, compiledJQ);
Query ret = SparqlParserUtilities.parseSparqlString(compiledJQ.toString());
return ret;
}
 
Example 10
Source File: SparqlConstraintImpl.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
private Set<ResultAnnotation> createResultAnnotations(String originalSelectQuery) {
    String prefixes = validator.getPrefixDeclarations().stream()
            .map(p -> "PREFIX " + p.getPrefix() + ": <" + p.getNamespace() + ">")
            .collect(Collectors.joining("\n"));

    String originalSelectClause = validator.getSparqlQuery().substring(0,validator.getSparqlQuery().indexOf('{'));
    String constructedQuery = prefixes + "\n" + originalSelectClause + getSparqlWhere()

            .replaceFirst("(?i)\\s*ASK\\s*\\{", "SELECT \\?this WHERE \\{");

    try {
        Query query = QueryFactory.create(constructedQuery);

        return ResultAnnotationParser.builder()
                .query(query)
                .shape(shape)
                .validator(validator)
                .canBindValueVariable(true)
                .build()
                .getResultAnnotations();
    } catch (Exception e) {

        throw new IllegalArgumentException(constructedQuery, e);
    }



}
 
Example 11
Source File: TriplePatternExtractorTest.java    From NLIWOD with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void extractTripleTest() {
	Query q = QueryFactory.create("prefix  dbp:  <http://dbpedia.org/resource/> " + "prefix  dbp2: <http://dbpedia.org/ontology/> " + "select  ?y ?c where  { dbp:total dbp2:thumbnail ?thumbnail. "
	        		+ "?thumbnail dbp2:thumbnail ?y. ?x dbp2:thumbnail ?c}");
	
	String realAnswer = "[?x @http://dbpedia.org/ontology/thumbnail ?c]";
	
	TriplePatternExtractor triplePatternExtractor = new TriplePatternExtractor();
	Set<Triple> answer = triplePatternExtractor.extractTriplePatterns(q, q.getProjectVars().get(1));
	Assert.assertTrue(realAnswer.equals(answer.toString()));
}
 
Example 12
Source File: DatasetWikidataTest.java    From NLIWOD with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void quickParseabilityTest() {
	List<IQuestion> questions = LoaderController.load(Dataset.QALD7_Train_Wikidata_en);
	questions.addAll(LoaderController.load(Dataset.QALD7_Test_Wikidata_en));
	for (IQuestion it : questions) {
		String sparqlQuery = it.getSparqlQuery();
		System.out.println(sparqlQuery);
		QueryFactory.create(sparqlQuery);
	}
}
 
Example 13
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 14
Source File: RDF2CSV.java    From IGUANA with GNU Affero General Public License v3.0 5 votes vote down vote up
private static Query createQuery(String taskID, Field[] fields) {
	StringBuilder vars = new StringBuilder();
	StringBuilder triples = new StringBuilder(taskID).append(" ?p ?uuid . ");
	triples.append("?expID <http://iguana-benchmark.eu/properties/task> "+taskID+" .");
	triples.append("?suiteId <http://iguana-benchmark.eu/properties/experiment> ?expID .");
	triples.append("?expID <http://iguana-benchmark.eu/properties/task> ?taskID FILTER(?taskID="+taskID+").");
	for (Field field : fields) {
		vars.append(field.getVar()).append(" ");
		triples.append(field.getTriples()).append(" ");
	}
	return QueryFactory.create("SELECT DISTINCT " + vars + " { " + triples + " }");
}
 
Example 15
Source File: QueryGenerationSelectFactory.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
@Override
public Query getSparqlQuery(TestCase testCase) {
    String query = this.getSparqlQueryAsString(testCase);
    try {
        return QueryFactory.create(query);
    } catch (QueryParseException e) {
        throw new IllegalArgumentException("Illegal query: \n" + query, e);
    }
}
 
Example 16
Source File: SPARQLEndpointExecution.java    From hypergraphql with Apache License 2.0 4 votes vote down vote up
@Override
public SPARQLExecutionResult call() {
    Map<String, Set<String>> resultSet = new HashMap<>();

    markers.forEach(marker -> resultSet.put(marker, new HashSet<>()));

    Model unionModel = ModelFactory.createDefaultModel();

    SPARQLServiceConverter converter = new SPARQLServiceConverter(schema);
    String sparqlQuery = converter.getSelectQuery(query, inputSubset, rootType);
    logger.debug(sparqlQuery);

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    Credentials credentials =
            new UsernamePasswordCredentials(this.sparqlEndpointService.getUser(), this.sparqlEndpointService.getPassword());
    credsProvider.setCredentials(AuthScope.ANY, credentials);
    HttpClient httpclient = HttpClients.custom()
            .setDefaultCredentialsProvider(credsProvider)
            .build();
    HttpOp.setDefaultHttpClient(httpclient);

    ARQ.init();
    Query jenaQuery = QueryFactory.create(sparqlQuery);

    QueryEngineHTTP qEngine = QueryExecutionFactory.createServiceRequest(this.sparqlEndpointService.getUrl(), jenaQuery);
    qEngine.setClient(httpclient);
    //qEngine.setSelectContentType(ResultsFormat.FMT_RS_XML.getSymbol());

    ResultSet results = qEngine.execSelect();

    results.forEachRemaining(solution -> {
        markers.stream().filter(solution::contains).forEach(marker ->
                resultSet.get(marker).add(solution.get(marker).asResource().getURI()));

        unionModel.add(this.sparqlEndpointService.getModelFromResults(query, solution, schema));
    });

    SPARQLExecutionResult sparqlExecutionResult = new SPARQLExecutionResult(resultSet, unionModel);
    logger.debug("Result: {}", sparqlExecutionResult);

    return sparqlExecutionResult;
}
 
Example 17
Source File: QUEPY.java    From NLIWOD with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Overriding Original search method to implement Quepy's two step requests for
 * QA
 */
@Override
public void search(IQuestion question, String language) throws Exception {
	String questionString;
	if (!question.getLanguageToQuestion().containsKey(language)) {
		return;
	}
	questionString = question.getLanguageToQuestion().get(language);
	log.debug(this.getClass().getSimpleName() + ": " + questionString);
	this.getParamMap().put(this.getQueryKey(), questionString);
	if (this.setLangPar) {
		this.getParamMap().put(this.getLangKey(), language);
	}
	HttpResponse response = this.getIsPostReq() ? fetchPostResponse(getUrl(), getParamMap())
			: fetchGetResponse(getUrl(), getParamMap());
	// Test if error occured
	if (response.getStatusLine().getStatusCode() >= 400) {
		throw new Exception("QUEPY Server could not answer due to: " + response.getStatusLine());
	}
	// Fetch the SPARQL
	String sparqlStr = null;
	JSONParser parser = new JSONParser();

	JSONObject responsejson = (JSONObject) parser.parse(responseparser.responseToString(response));
	JSONArray queriesArr = (JSONArray) responsejson.get("queries");
	for (int i = 0; i < queriesArr.size(); i++) {
		JSONObject queryObj = (JSONObject) queriesArr.get(i);
		if (queryObj.get("language").toString().equalsIgnoreCase("sparql") && queryObj.get("query") != null) {
			sparqlStr = queryObj.get("query").toString();
			break;
		}
	}
	if (sparqlStr != null) {
		HashSet<String> result = new HashSet<String>();
		question.setSparqlQuery(sparqlStr);
		// Fetch results using sparql
		Query query = QueryFactory.create(sparqlStr);
		// Remote execution.
		QueryExecution qexec = QueryExecutionFactory.sparqlService(SPARQL_ENDPOINT, query);
		// Set the DBpedia specific timeout.
		((QueryEngineHTTP) qexec).addParam("timeout", "10000");
		// Execute.
		ResultSet rs = qexec.execSelect();
		// Get the values and push them to the question
		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			Iterator<String> varIt = qs.varNames();
			while (varIt.hasNext()) {
				RDFNode node = qs.get(varIt.next());
				result.add(node.asLiteral().getString());
			}
		}
		question.setGoldenAnswers(result);
	}
}
 
Example 18
Source File: SPINRulesTest.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
public static Query parseToJenaQuery(String queryString)  {
	return QueryFactory.create(queryString);
}
 
Example 19
Source File: PlanFactory.java    From sparql-generate with Apache License 2.0 4 votes vote down vote up
/**
 * Makes a {@code RootPlan} for a query.
 *
 * @param query the Query.
 * @return the RootPlan.
 */
private static RootPlan make(final SPARQLExtQuery query) {
    Objects.requireNonNull(query, "The query must not be null");
    if (query.hasEmbeddedExpressions()) {
        LOG.debug("Query has embedded expressions:\n" + query);
        String qs = query.toString();
        SPARQLExtQuery query2;
        if (query.isSubQuery()) {
            query2 = (SPARQLExtQuery) ParserSPARQLExt.parseSubQuery(query, qs);
            query2.normalizeXExpr();
            query2.normalizeAggregates();
        } else {
            query2 = (SPARQLExtQuery) QueryFactory.create(qs, SPARQLExt.SYNTAX);
            query2.normalizeXExpr();
            query2.normalizeBNode();
            query2.normalizeAggregates();
        }
        return make(query2);
    }
    
    LOG.trace("Making plan for query without embedded expressions\n" + query);
    DatasetDeclarationPlan datasetDeclarationPlan = new DatasetDeclarationPlan(query);

    List<BindingsClausePlan> iteratorAndSourcePlans = new ArrayList<>();
    if (query.hasBindingClauses()) {
        for (Element el : query.getBindingClauses()) {
            BindingsClausePlan iteratorOrSourcePlan;
            if (el instanceof ElementIterator) {
                ElementIterator elementIterator = (ElementIterator) el;
                iteratorOrSourcePlan = makeIteratorPlan(elementIterator);
            } else if (el instanceof ElementSource) {
                ElementSource elementSource = (ElementSource) el;
                iteratorOrSourcePlan = makeSourcePlan(elementSource);
            } else if (el instanceof ElementBind) {
                ElementBind elementBind = (ElementBind) el;
                iteratorOrSourcePlan = makeBindPlan(elementBind);
            } else {
                throw new UnsupportedOperationException("should not reach"
                        + " this point");
            }
            iteratorAndSourcePlans.add(iteratorOrSourcePlan);
        }
    }

    /*
    * TEMPLATE queries are translated into a SELECT with project 
    * variable ?out.
     */
    final SelectPlan selectPlan = makeSelectPlan(query);

    if (query.isTemplateType()) {
     final TemplatePlan templatePlan = makeTemplatePlan(query);
        return new RootPlan(
                query, datasetDeclarationPlan, iteratorAndSourcePlans,
                selectPlan, templatePlan);
    }
    if (query.isGenerateType()) {
     final GeneratePlan generatePlan;
     if (query.hasGenerateClause()) {
         generatePlan = makeGenerateFormPlan(query);
     } else {
         generatePlan = makeGenerateNamedPlan(query);
     }
     return new RootPlan(
             query, datasetDeclarationPlan, iteratorAndSourcePlans,
             selectPlan, generatePlan);
    }
    return new RootPlan(query, datasetDeclarationPlan, iteratorAndSourcePlans, selectPlan);
}
 
Example 20
Source File: TestAllTypes.java    From incubator-taverna-language with Apache License 2.0 4 votes vote down vote up
@Test
	public void convert() throws Exception {
		assertFalse(allTypesWfdesc.exists());
		WorkflowBundleIO io = new WorkflowBundleIO();
		WorkflowBundle wfBundle = io.readBundle(allTypesT2flow, null);
		io.writeBundle(wfBundle, allTypesWfdesc,
				"text/vnd.wf4ever.wfdesc+turtle");
		assertTrue(allTypesWfdesc.exists());
	
		Model allTypes = RDFDataMgr.loadModel(allTypesWfdesc.getAbsolutePath(), Lang.TURTLE);

		
		
		ByteArrayOutputStream out = new ByteArrayOutputStream();

		Query query = QueryFactory.create("PREFIX wfdesc: <http://purl.org/wf4ever/wfdesc#> "
				+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> "
				+ "PREFIX owl: <http://www.w3.org/2002/07/owl#> "
				+ "SELECT ?wf ?proc ?procType ?procLabel "
				+ "WHERE {"
				+ "	?wf a wfdesc:Workflow;"
				+ "       wfdesc:hasSubProcess ?proc. "
				+ " ?proc rdfs:label ?procLabel ."
				// Ignore non-specific types
				+ "OPTIONAL { ?proc a ?procType . FILTER (?procType != wfdesc:Description && ?procType != wfdesc:Process && ?procType != owl:Thing) }"
				+ "} " + "ORDER BY ?wf ") ;
		

		try (QueryExecution qexec = QueryExecutionFactory.create(query, allTypes)) {
		    ResultSet results = qexec.execSelect() ;
		    
		    //results.forEachRemaining(
		}
		

//		ObjectMapper mapper = new ObjectMapper();
//		JsonNode jsonNode = mapper.readValue(out.toByteArray(), JsonNode.class);
//		String oldWf = null;
//		for (JsonNode binding : jsonNode.path("results").path("bindings")) {
//			String wf = binding.path("wf").path("value").asText();
//			if (!wf.equals(oldWf)) {
//				//System.out.println(wf);
//				oldWf = wf;
//			}
//			String proc = binding.path("proc").path("value").asText();
//			assertNotNull(proc);
//			String procType = binding.path("procType").path("value").asText();
//			String procTypeShort = null;
//			if (procType == null) 
//				continue;
//			procTypeShort = URI.create(procType).getFragment();
//			assertNotNull(procTypeShort);
//			String procLabel = binding.path("procLabel").path("value").asText();
//			assertNotNull(procLabel);
//			//System.out.println(" Processor " + procLabel + " (" + procTypeShort
//			//		+ ")");
//			//System.out.println("   " + proc + " " + procType);
//		}

		out.reset();

		Query query2 = QueryFactory.create(
				"PREFIX wfdesc: <http://purl.org/wf4ever/wfdesc#> "
						+ " PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> "
						+ " PREFIX owl: <http://www.w3.org/2002/07/owl#> "
						+ " SELECT ?wf ?fromProc ?toProc ?fromProcLabel ?toProcLabel "
						+ " WHERE {" + "	?wf a wfdesc:Workflow;"
						+ "       wfdesc:hasSubProcess ?fromProc,?toProc ;"
						+ "       wfdesc:hasDataLink ?link . "
						+ " ?link wfdesc:hasSource ?fromPort; "
						+ "      wfdesc:hasSink ?toPort ."
						+ " ?fromProc wfdesc:hasOutput ?fromPort ;"
						+ "           rdfs:label ?fromProcLabel ."
						+ " ?toProc wfdesc:hasInput ?toPort ;"
						+ "         rdfs:label ?toProcLabel ." + "} "
						+ "ORDER BY ?wf ");
		 //System.out.println(out.toString());
//		jsonNode = mapper.readValue(out.toByteArray(), JsonNode.class);
//		for (JsonNode binding : jsonNode.path("results").path("bindings")) {
//			String wf = binding.path("wf").path("value").asText();
//			if (!wf.equals(oldWf)) {
//				//System.out.println(wf);
//				oldWf = wf;
//			}
//			String fromProcLabel = binding.path("fromProcLabel").path("value")
//					.asText();
//			assertNotNull(fromProcLabel);
//			String toProcLabel = binding.path("toProcLabel").path("value")
//					.asText();
//			assertNotNull(toProcLabel);
//			String fromProc = binding.path("fromProc").path("value").asText();
//			assertNotNull(fromProc);
//			String toProc = binding.path("toProc").path("value").asText();
//			assertNotNull(toProc);
//			//System.out.print(" " + fromProcLabel);
//			//System.out.println(" -> " + toProcLabel);
//			//System.out.println("    " + fromProc + " -> " + toProc);
//		}

	}