org.apache.jena.query.QuerySolution Java Examples

The following examples show how to use org.apache.jena.query.QuerySolution. 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: DatasetGenerator.java    From NLIWOD with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void updateGoldenAnswers(QueryExecutionFactory qef, IQuestion q) {
	Set<String> uris = new HashSet<>();
	if (null != q && null != q.getSparqlQuery() && !q.getSparqlQuery().contains("ASK")) {
		try (QueryExecution qe = qef.createQueryExecution(q.getSparqlQuery())) {
			ResultSet rs = qe.execSelect();
			while (rs.hasNext()) {
				QuerySolution qs = rs.next();

				RDFNode node = qs.get("uri");

				if (node != null && node.isResource()) {
					uris.add(node.asResource().getURI());
				}
			}
		}
		q.setGoldenAnswers(uris);
	} else {// TODO what happens if q is null?
	}

}
 
Example #2
Source File: SHACLSPARQLARQFunction.java    From shacl with Apache License 2.0 6 votes vote down vote up
@Override
   public NodeValue executeBody(Dataset dataset, Model defaultModel, QuerySolution bindings) {
    try( QueryExecution qexec = createQueryExecution(dataset, defaultModel, bindings) ) {
        if(arqQuery.isAskType()) {
            boolean result = qexec.execAsk();
            return NodeValue.makeBoolean(result);
        }
        else {
            ResultSet rs = qexec.execSelect();
            if(rs.hasNext()) {
                QuerySolution s = rs.nextSolution();
                List<String> resultVars = rs.getResultVars();
                String varName = resultVars.get(0);
                RDFNode resultNode = s.get(varName);
                if(resultNode != null) {
                    return NodeValue.makeNode(resultNode.asNode());
                }
            }
            throw new ExprEvalException("Empty result set for SHACL function");
        }
    }
}
 
Example #3
Source File: AbstractSPARQLExecutor.java    From shacl with Apache License 2.0 6 votes vote down vote up
private void addDefaultMessages(ValidationEngine engine, Resource messageHolder, Resource fallback, Resource result, 
			QuerySolution bindings, QuerySolution solution) {
	boolean found = false;
	for(Statement s : messageHolder.listProperties(SH.message).toList()) {
		if(s.getObject().isLiteral()) {
			QuerySolutionMap map = new QuerySolutionMap();
			map.addAll(bindings);
			map.addAll(solution);
			engine.addResultMessage(result, s.getLiteral(), map);
			found = true;
		}
	}
	if(!found && fallback != null) {
		addDefaultMessages(engine, fallback, null, result, bindings, solution);
	}
}
 
Example #4
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 #5
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 #6
Source File: NashornScriptEngine.java    From shacl with Apache License 2.0 6 votes vote down vote up
@Override
public Object invokeFunction(String functionName, QuerySolution bindings) throws javax.script.ScriptException, java.lang.NoSuchMethodException {
	List<String> functionParams = getFunctionParameters(functionName);
	Object[] params = new Object[functionParams.size()];
	Iterator<String> varNames = bindings.varNames();
	while(varNames.hasNext()) {
		String varName = varNames.next();
		int index = functionParams.indexOf(varName);
		if(index < 0) {
			index = functionParams.indexOf("$" + varName);
		}
		if(index >= 0) {
			RDFNode value = bindings.get(varName);
			if(value != null) {
				params[index] = JSFactory.asJSTerm(value.asNode());
			}
		}
	}
	return invokeFunctionOrdered(functionName, params);
}
 
Example #7
Source File: JenaUtil.java    From shacl with Apache License 2.0 6 votes vote down vote up
/**
 * Calls a SPARQL expression and returns the result, using some initial bindings.
 *
 * @param expression     the expression to execute (must contain absolute URIs)
 * @param initialBinding the initial bindings for the unbound variables
 * @param dataset        the query Dataset or null for default
 * @return the result or null
 */
public static Node invokeExpression(String expression, QuerySolution initialBinding, Dataset dataset) {
    if (dataset == null) {
        dataset = ARQFactory.get().getDataset(ModelFactory.createDefaultModel());
    }
    Query query = ARQFactory.get().createExpressionQuery(expression);
    try(QueryExecution qexec = ARQFactory.get().createQueryExecution(query, dataset, initialBinding)) {
        ResultSet rs = qexec.execSelect();
        Node result = null;
        if (rs.hasNext()) {
            QuerySolution qs = rs.next();
            String firstVarName = rs.getResultVars().get(0);
            RDFNode rdfNode = qs.get(firstVarName);
            if (rdfNode != null) {
                result = rdfNode.asNode();
            }
        }
        return result;
    }
}
 
Example #8
Source File: JenaUtil.java    From shacl with Apache License 2.0 6 votes vote down vote up
/**
 * Turns a QuerySolution into a Binding. 
 * @param map  the input QuerySolution
 * @return a Binding or null if the input is null
 */
public static Binding asBinding(final QuerySolution map) {
	if(map != null) {
		BindingHashMap result = new BindingHashMap();
		Iterator<String> varNames = map.varNames();
		while(varNames.hasNext()) {
			String varName = varNames.next();
			RDFNode node = map.get(varName);
			if(node != null) {
				result.add(Var.alloc(varName), node.asNode());
			}
		}
		return result;
	}
	else {
		return null;
	}
}
 
Example #9
Source File: ARQFactory.java    From shacl with Apache License 2.0 6 votes vote down vote up
public QueryExecution createQueryExecution(Query query, Dataset dataset, QuerySolution initialBinding) {
		if(!query.getGraphURIs().isEmpty() || !query.getNamedGraphURIs().isEmpty()) {
			dataset = new FromDataset(dataset, query);
		}
		
		if ( LOG_QUERIES ) {
		    // And the data - can be long.
//    		System.err.println("~~ ~~");
//    		RDFDataMgr.write(System.err, dataset.getDefaultModel(), Lang.TTL);
    		System.err.println("~~ ~~");
    		System.err.println(initialBinding);
    		System.err.println(query);
		}
		
		QueryExecution qexec = QueryExecutionFactoryFilter.get().create(query, dataset, initialBinding);
		adjustQueryExecution(qexec);
		return qexec;
	}
 
Example #10
Source File: PubchemMeshSynonyms.java    From act with GNU General Public License v3.0 6 votes vote down vote up
public Map<PubchemSynonymType, Set<String>> fetchPubchemSynonymsFromCID(String cid) {
  // The clone method has its own implementation in the SelectBuilder. Thus safe to use!
  SelectBuilder sb = PUBCHEM_SYNO_QUERY_TMPL.clone();
  sb.setVar(Var.alloc("compound"), String.format("compound:%s", cid));
  Query query = sb.build();
  LOGGER.debug("Executing SPARQL query: %s", query.toString());
  Map<PubchemSynonymType, Set<String>> map = new HashMap<>();

  try (QueryExecution queryExecution = QueryExecutionFactory.sparqlService(sparqlService, query)) {
    ResultSet results = queryExecution.execSelect();
    while(results.hasNext()) {
      QuerySolution solution = results.nextSolution();
      String cheminfId = solution.getResource("type").getLocalName();
      String synonym = solution.getLiteral("value").getString();
      LOGGER.debug("Found synonym %s with type %s", synonym, cheminfId);
      PubchemSynonymType synonymType = PubchemSynonymType.getByCheminfId(cheminfId);
      Set synonyms = map.get(synonymType);
      if (synonyms == null) {
        synonyms = new HashSet<>();
        map.put(synonymType, synonyms);
      }
      synonyms.add(synonym);
    }
  }
  return map;
}
 
Example #11
Source File: 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 #12
Source File: Service.java    From hypergraphql with Apache License 2.0 6 votes vote down vote up
private Model buildModel(QuerySolution results, JsonNode currentNode , HGQLSchema schema) {

        Model model = ModelFactory.createDefaultModel();

        FieldConfig propertyString = schema.getFields().get(currentNode.get("name").asText());
        TypeConfig targetTypeString = schema.getTypes().get(currentNode.get("targetName").asText());

        populateModel(results, currentNode, model, propertyString, targetTypeString);

        QueryFieldConfig queryField = schema.getQueryFields().get(currentNode.get("name").asText());

        if (queryField != null) {

            String typeName = (currentNode.get("alias").isNull()) ? currentNode.get("name").asText() : currentNode.get("alias").asText();
            Resource object = results.getResource(currentNode.get("nodeId").asText());
            Resource subject = model.createResource(HGQL_QUERY_URI);
            Property predicate = model.createProperty("", HGQL_QUERY_NAMESPACE + typeName);
            model.add(subject, predicate, object);
        }
        return model;
    }
 
Example #13
Source File: ITER_Call_Select.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
private List<List<NodeValue>> getListNodeValues(ResultSet result) {
    List<String> resultVars = result.getResultVars();
    List<List<NodeValue>> listNodeValues = new ArrayList<>();
    while (result.hasNext()) {
        List<NodeValue> nodeValues = new ArrayList<>();
        QuerySolution sol = result.next();
        for (String var : resultVars) {
            RDFNode rdfNode = sol.get(var);
            if (rdfNode != null) {
                NodeValue n = new NodeValueNode(rdfNode.asNode());
                nodeValues.add(n);
            } else {
                nodeValues.add(null);
            }
        }
        listNodeValues.add(nodeValues);
    }
    return listNodeValues;
}
 
Example #14
Source File: SPARQLExtIteratorFunction.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
private List<List<NodeValue>> getListNodeValues(ResultSet result) {
	List<String> resultVars = result.getResultVars();
	List<List<NodeValue>> listNodeValues = new ArrayList<>();
	while (result.hasNext()) {
		List<NodeValue> nodeValues = new ArrayList<>();
		QuerySolution sol = result.next();
		for (String var : resultVars) {
			RDFNode rdfNode = sol.get(var);
			if (rdfNode != null) {
				NodeValue n = new NodeValueNode(rdfNode.asNode());
				nodeValues.add(n);
			} else {
				nodeValues.add(null);
			}
		}
		listNodeValues.add(nodeValues);
	}
	return listNodeValues;
}
 
Example #15
Source File: DB2DescribeHandler.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
public void describe(Resource r) {
	// Default model.
	DB2Closure.closure(otherModel(r, dataset.getDefaultModel()), false, acc, resources);

	String query = "SELECT ?g { GRAPH ?g { <" + r.getURI() + "> ?p ?o } }";
	QueryExecution qExec = RdfStoreQueryExecutionFactory.create(query,
			dataset);

	ResultSet rs = qExec.execSelect();
	for (; rs.hasNext();) {
		QuerySolution qs = rs.next();
		String gName = qs.getResource("g").getURI(); // mdb for DB2
		Model model = dataset.getNamedModel(gName);
		Resource r2 = otherModel(r, model);
		DB2Closure.closure(r2, false, acc, resources);
	}

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

			String columnName = columnNames.get(i);
			RDFNode rdfNode = row.get(columnName);
			getValue(rdfNode, record);
			getMetaData(rdfNode, fieldMeta);
		}
		dataStore.appendRecord(record);
	}
}
 
Example #17
Source File: Service.java    From hypergraphql with Apache License 2.0 6 votes vote down vote up
private Model buildModel(QuerySolution results, JsonNode currentNode , HGQLSchema schema) {

        Model model = ModelFactory.createDefaultModel();

        FieldConfig propertyString = schema.getFields().get(currentNode.get("name").asText());
        TypeConfig targetTypeString = schema.getTypes().get(currentNode.get("targetName").asText());

        populateModel(results, currentNode, model, propertyString, targetTypeString);

        QueryFieldConfig queryField = schema.getQueryFields().get(currentNode.get("name").asText());

        if (queryField != null) {

            String typeName = (currentNode.get("alias").isNull()) ? currentNode.get("name").asText() : currentNode.get("alias").asText();
            Resource object = results.getResource(currentNode.get("nodeId").asText());
            Resource subject = model.createResource(HGQL_QUERY_URI);
            Property predicate = model.createProperty("", HGQL_QUERY_NAMESPACE + typeName);
            model.add(subject, predicate, object);
        }
        return model;
    }
 
Example #18
Source File: SPARQLSubstitutions.java    From shacl with Apache License 2.0 5 votes vote down vote up
public static Literal withSubstitutions(Literal template, QuerySolution bindings, Function<RDFNode,String> labelFunction) {
	StringBuffer buffer = new StringBuffer();
	String labelTemplate = template.getLexicalForm();
	for(int i = 0; i < labelTemplate.length(); i++) {
		if(i < labelTemplate.length() - 3 && labelTemplate.charAt(i) == '{' && (labelTemplate.charAt(i + 1) == '?' || labelTemplate.charAt(i + 1) == '$')) {
			int varEnd = i + 2;
			while(varEnd < labelTemplate.length()) {
				if(labelTemplate.charAt(varEnd) == '}') {
					String varName = labelTemplate.substring(i + 2, varEnd);
					RDFNode varValue = bindings.get(varName);
					if(varValue != null) {
						if(labelFunction != null) {
							buffer.append(labelFunction.apply(varValue));
						}
						else if(varValue instanceof Resource) {
							buffer.append(RDFLabels.get().getLabel((Resource)varValue));
						}
						else if(varValue instanceof Literal) {
							buffer.append(varValue.asNode().getLiteralLexicalForm());
						}
					}
					break;
				}
				else {
					varEnd++;
				}
			}
			i = varEnd;
		}
		else {
			buffer.append(labelTemplate.charAt(i));
		}
	}
	if(template.getLanguage().isEmpty()) {
		return ResourceFactory.createTypedLiteral(buffer.toString());
	}
	else {
		return ResourceFactory.createLangLiteral(buffer.toString(), template.getLanguage());
	}
}
 
Example #19
Source File: SHACLSPARQLARQFunction.java    From shacl with Apache License 2.0 5 votes vote down vote up
private QueryExecution createQueryExecution(Dataset dataset, Model defaultModel, QuerySolution bindings) {
    if(dataset == null) {
           return ARQFactory.get().createQueryExecution(arqQuery, defaultModel, bindings);
    }
    else {
    	Dataset newDataset = new DatasetWithDifferentDefaultModel(defaultModel, dataset);
    	return ARQFactory.get().createQueryExecution(arqQuery, newDataset, bindings);
    }
}
 
Example #20
Source File: QueryExecutionFactoryFilter.java    From shacl with Apache License 2.0 5 votes vote down vote up
private void analyzeRequest(Query query, Model model, QuerySolution initialBinding) {
       printQuery(query, initialBinding);

	if(logger.isTraceEnabled()) {	
		logger.trace("QUERY[" + analyzeQuery(query) 
			+ "]\nMODEL[" + analyzeModel(model) + "]" 
			+  serializeBindings(initialBinding));
	}
}
 
Example #21
Source File: DBPediaService.java    From baleen with Apache License 2.0 5 votes vote down vote up
private Set<DefaultCandidate> getCandidates(ResultSet rs, String idField, String nameField) {
  Set<DefaultCandidate> candidates = new HashSet<>();
  while (rs.hasNext()) {
    QuerySolution qs = rs.next();
    Map<String, String> fieldsMap = new HashMap<>();
    qs.varNames()
        .forEachRemaining(
            varName -> fieldsMap.put(varName, new DBPediaLanguageString(qs.get(varName)).raw()));
    DBPediaLanguageString id = new DBPediaLanguageString(qs.get(idField));
    DBPediaLanguageString name = new DBPediaLanguageString(qs.get(nameField));
    candidates.add(new DefaultCandidate(id.raw(), name.raw(), fieldsMap));
  }
  return candidates;
}
 
Example #22
Source File: AbstractJSExecutor.java    From shacl with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private void createValidationResultFromJSObject(ValidationEngine engine, Constraint constraint, RDFNode focusNode,
		Resource messageHolder, QuerySolution bindings, Object ro) {
	Resource result = createValidationResult(engine, constraint, focusNode);
	if(ro instanceof Map) {
		Object value = ((Map)ro).get("value");
		if(value instanceof JSTerm) {
			Node resultValueNode = JSFactory.getNode(value);
			if(resultValueNode != null) {
				result.addProperty(SH.value, result.getModel().asRDFNode(resultValueNode));
			}
		}
		Object message = ((Map)ro).get("message");
		if(message instanceof String) {
			result.addProperty(SH.resultMessage, (String)message);
		}
		Object path = ((Map)ro).get("path");
		if(path != null) {
			Node pathNode = JSFactory.getNode(path);
			if(pathNode != null && pathNode.isURI()) {
				result.addProperty(SH.resultPath, result.getModel().asRDFNode(pathNode));
			}
		}
	}
	else if(ro instanceof String) {
		result.addProperty(SH.resultMessage, (String)ro);
	}
	if(!result.hasProperty(SH.resultMessage)) {
		addDefaultMessages(engine, constraint, messageHolder, constraint.getComponent(), result, bindings, ro instanceof Map ? (Map)ro : null);
	}
}
 
Example #23
Source File: OneM2MSubscribeUriMapper.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public List<String> getSubscribeUri() {
	List<String> result = new ArrayList<String>();
	String query = this.makeQueryString();
	String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.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("uri").toString().replaceAll(baseuri, ""))));
	}
	return result;
}
 
Example #24
Source File: VarUtils.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
public static Binding getBinding(
        final QuerySolution sol) {
    final BindingMap binding = BindingFactory.create();
    for (Iterator<String> it = sol.varNames(); it.hasNext();) {
        String varName = it.next();
        binding.add(allocVar(varName), sol.get(varName).asNode());
    }
    return binding;
}
 
Example #25
Source File: VarUtils.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
public static List<Var> getVariables(
        final QuerySolution sol) {
    final List<Var> variables = new ArrayList<>();
    for (Iterator<String> it = sol.varNames(); it.hasNext();) {
        variables.add(allocVar(it.next()));
    }
    return variables;
}
 
Example #26
Source File: EvalUtils.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
public static Binding createBinding(QuerySolution sol) {
	final BindingMap binding = BindingFactory.create();
	for (Iterator<String> it = sol.varNames(); it.hasNext();) {
		final String varName = it.next();
		binding.add(VarUtils.allocVar(varName), sol.get(varName).asNode());
	}
	return binding;
}
 
Example #27
Source File: EntitySPARQLReader.java    From JedAIToolkit with Apache License 2.0 5 votes vote down vote up
private void readEndpoint(String endpointUrl) throws IOException {
    //read each ntriples
    //get spo, create a separate profile for each separate subject,
    //with Attribute=predicate and Value=object
    final String sparqlQueryString1 = "select ?a ?b ?c where {?a ?b ?c}";

    final Query query = QueryFactory.create(sparqlQueryString1);
    try (QueryExecution qexec = QueryExecutionFactory.sparqlService(endpointUrl, query)) {
        final ResultSet results = qexec.execSelect();
        //ResultSetFormatter.out(System.out, results, query);
        //results = qexec.execSelect();
        
        while (results.hasNext()) {
            final QuerySolution qs = results.next();
            
            final String sub = qs.get("a").toString();
            final String pred = qs.get("b").toString();
            final String obj = qs.get("c").toString();
            if (attributesToExclude.contains(pred)) {
                continue;
            }
            
            //if already exists a profile for the subject, simply add po as <Att>-<Value>
            EntityProfile entityProfile = urlToEntity.get(sub);
            if (entityProfile == null) {
                entityProfile = new EntityProfile(sub);
                entityProfiles.add(entityProfile);
                urlToEntity.put(sub, entityProfile);
            }
            
            if (!obj.isEmpty()) {
                entityProfile.addAttribute(pred, obj);
            }
        }
    }
    //ResultSetFormatter.out(System.out, results, query);
    //results = qexec.execSelect();
}
 
Example #28
Source File: ClassSurfaceForms.java    From NLIWOD with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {

		CLASS_SURFACE_FORMS = DIRECTORY + "class_surface_forms.ttl";

		// create an empty model
		Model inputModel = ModelFactory.createDefaultModel();

		// use the FileManager to find the input file
		InputStream in = FileManager.get().open(DBPEDIA_CLASSE_FILE);
		if (in == null) {
			throw new IllegalArgumentException("File: " + DBPEDIA_CLASSE_FILE + " not found");
		}

		// read the RDF/XML file
		inputModel.read(in, null, "N-TRIPLE");

		Model outputModel = ModelFactory.createDefaultModel();
		QueryExecution qExec = QueryExecutionFactory
				.create("SELECT ?s ?label WHERE{?s a <http://www.w3.org/2002/07/owl#Class>."
						+ " ?s <http://www.w3.org/2000/01/rdf-schema#label> ?label. "
						+ "FILTER (lang(?label) = \"en\")}", inputModel);
		ResultSet rs = qExec.execSelect();
		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			Resource uri = qs.get("?s").asResource();
			RDFNode label = qs.get("?label");
			StatementImpl s = new StatementImpl(uri, RDFS.label, label);
			outputModel.add(s);

		}

		qExec.close();

		FileOutputStream outputFile = new FileOutputStream(CLASS_SURFACE_FORMS);
		RDFDataMgr.write(outputFile, outputModel, RDFFormat.NTRIPLES);

	}
 
Example #29
Source File: SPARQLSubstitutions.java    From shacl with Apache License 2.0 5 votes vote down vote up
public static QueryExecution createQueryExecution(Query query, Dataset dataset, QuerySolution bindings) {
	if(USE_TRANSFORM && bindings != null) {
		Map<Var,Node> substitutions = new HashMap<Var,Node>();
		Iterator<String> varNames = bindings.varNames();
		while(varNames.hasNext()) {
			String varName = varNames.next();
			substitutions.put(Var.alloc(varName), bindings.get(varName).asNode());
		}
		Query newQuery = JenaUtil.queryWithSubstitutions(query, substitutions);
		return ARQFactory.get().createQueryExecution(newQuery, dataset);
	}
	else {
		return ARQFactory.get().createQueryExecution(query, dataset, bindings);
	}
}
 
Example #30
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;
}