Java Code Examples for org.apache.jena.query.QuerySolution

The following examples show how to use org.apache.jena.query.QuerySolution. These examples are extracted from open source projects. 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 Project: hypergraphql   Author: hypergraphql   File: Service.java    License: 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 #2
Source Project: Knowage-Server   Author: KnowageLabs   File: SPARQLDataReader.java    License: 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 #3
Source Project: hypergraphql   Author: semantic-integration   File: Service.java    License: 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 #4
Source Project: act   Author: 20n   File: PubchemMeshSynonyms.java    License: GNU General Public License v3.0 6 votes vote down vote up
public Map<PubchemSynonymType, Set<String>> fetchPubchemSynonymsFromCID(String cid) {
  // The clone method has its own implementation in the SelectBuilder. Thus safe to use!
  SelectBuilder sb = PUBCHEM_SYNO_QUERY_TMPL.clone();
  sb.setVar(Var.alloc("compound"), String.format("compound:%s", cid));
  Query query = sb.build();
  LOGGER.debug("Executing SPARQL query: %s", query.toString());
  Map<PubchemSynonymType, Set<String>> map = new HashMap<>();

  try (QueryExecution queryExecution = QueryExecutionFactory.sparqlService(sparqlService, query)) {
    ResultSet results = queryExecution.execSelect();
    while(results.hasNext()) {
      QuerySolution solution = results.nextSolution();
      String cheminfId = solution.getResource("type").getLocalName();
      String synonym = solution.getLiteral("value").getString();
      LOGGER.debug("Found synonym %s with type %s", synonym, cheminfId);
      PubchemSynonymType synonymType = PubchemSynonymType.getByCheminfId(cheminfId);
      Set synonyms = map.get(synonymType);
      if (synonyms == null) {
        synonyms = new HashSet<>();
        map.put(synonymType, synonyms);
      }
      synonyms.add(synonym);
    }
  }
  return map;
}
 
Example #5
Source Project: act   Author: 20n   File: PubchemMeshSynonyms.java    License: 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 #6
Source Project: quetzal   Author: Quetzal-RDF   File: DB2DescribeHandler.java    License: 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 #7
Source Project: NLIWOD   Author: dice-group   File: DatasetGenerator.java    License: 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 #8
Source Project: sparql-generate   Author: sparql-generate   File: SPARQLExtIteratorFunction.java    License: 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 #9
Source Project: sparql-generate   Author: sparql-generate   File: ITER_Call_Select.java    License: 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 #10
Source Project: shacl   Author: TopQuadrant   File: ARQFactory.java    License: 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 #11
Source Project: shacl   Author: TopQuadrant   File: JenaUtil.java    License: 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 #12
Source Project: shacl   Author: TopQuadrant   File: JenaUtil.java    License: 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 #13
Source Project: shacl   Author: TopQuadrant   File: AbstractSPARQLExecutor.java    License: 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 #14
Source Project: shacl   Author: TopQuadrant   File: SHACLSPARQLARQFunction.java    License: 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 #15
Source Project: shacl   Author: TopQuadrant   File: NashornScriptEngine.java    License: 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 #16
Source Project: trainbenchmark   Author: ftsrg   File: JenaQuery.java    License: 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 #17
Source Project: incubator-taverna-language   Author: apache   File: TestAnnotationTools.java    License: 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 #18
Source Project: RDFstarTools   Author: RDFstar   File: TextOutputStar.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected String getVarValueAsString(QuerySolution rBind, String varName) {
    final RDFNode obj = rBind.get(varName);

    if ( obj == null ) {
        return super.getVarValueAsString(rBind, varName);
    }
    else if ( obj.asNode() instanceof Node_Triple ) {
    	final Triple t = ( (Node_Triple) obj.asNode() ).get();
    	return getAsString(t);
    }
    else {
    	return FmtUtils.stringForRDFNode(obj, context);
    }
}
 
Example #19
Source Project: RDFstarTools   Author: RDFstar   File: TextOutputStarTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void nested1() {
	final MyTextOutput o = new MyTextOutput( getPrefixMappingForTests() );
	
	final Node u = NodeFactory.createURI("http://example.com/i");
	final Node n1 = new Node_Triple(new Triple(u, u, u));
	final Node n2 = new Node_Triple(new Triple(n1, u, u));
	final QuerySolution s = createQuerySolution( "?t", n2 );		
	final String result = o.get(s, "?t");

	assertEquals("<< ex:i ex:i ex:i >> ex:i ex:i ", result);
}
 
Example #20
Source Project: RDFstarTools   Author: RDFstar   File: TextOutputStarTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void nested2() {
	final MyTextOutput o = new MyTextOutput( getPrefixMappingForTests() );
	
	final Node u = NodeFactory.createURI("http://example.com/i");
	final Node n1 = new Node_Triple(new Triple(u, u, u));
	final Node n2 = new Node_Triple(new Triple(u, u, n1));
	final QuerySolution s = createQuerySolution( "?t", n2 );		
	final String result = o.get(s, "?t");

	assertEquals("ex:i ex:i << ex:i ex:i ex:i >> ", result);
}
 
Example #21
Source Project: RDFUnit   Author: AKSW   File: TestCaseWithTarget.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public RDFNode getFocusNode(QuerySolution solution) {

    String focusVar = getVariableAnnotations().stream()
            .filter(ra -> ra.getAnnotationProperty().equals(SHACL.focusNode))
            .map(ResultAnnotation::getAnnotationVarName)
            .filter(Optional::isPresent)
            .map(Optional::get)
            .findFirst()
            .orElse(CommonNames.This);
    return solution.get(focusVar);
}
 
Example #22
Source Project: rdf2neo   Author: Rothamsted   File: RdfDataManager.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Similarly to {@link #getCyNode(Resource, String, String)}, uses a binding (i.e., row) from a 
 * {@link CyRelationLoadingHandler#getRelationTypesSparql() relation type query} and creates a new {@link CyRelation}
 * with the RDF mapped data.
 */
public CyRelation getCyRelation ( QuerySolution relRow )
{		
	Resource relRes = relRow.get ( "iri" ).asResource ();
	CyRelation cyRelation = new CyRelation ( relRes.getURI () );
	
	cyRelation.setType ( this.getCypherId ( relRow.get ( "type" ), this.getCyRelationTypeIdConverter () ) );

	cyRelation.setFromIri ( relRow.get ( "fromIri" ).asResource ().getURI () );
	cyRelation.setToIri ( relRow.get ( "toIri" ).asResource ().getURI () );
			
	return cyRelation;
}
 
Example #23
Source Project: rdf2neo   Author: Rothamsted   File: RdfDataManager.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * If sparql is null, just doesn't do anything. This is useful in the rdf2neo context, since there are configured
 * queries that are optional. 
 */
@Override
public long processSelect ( String logPrefix, String sparql, Consumer<QuerySolution> action )
{
	if ( sparql == null ) {
		log.debug ( "null SPARQL for {}, skipping", logPrefix );
		return 0;
	}
	
	return super.processSelect ( logPrefix, sparql, action );
}
 
Example #24
Source Project: rdf2neo   Author: Rothamsted   File: CyRelationLoadingProcessor.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * This takes the relations mapped via {@link CyRelationLoadingHandler#getRelationTypesSparql()} and creates
 * sets of {@link QuerySolution}s that are sent to {@link CyRelationLoadingHandler} tasks.
 */
public void process ( RdfDataManager rdfMgr, Object...opts )
{
	log.info ( "Starting Cypher Relations Loading" );
	
	CyRelationLoadingHandler handler = this.getBatchJob ();

	// processNodeIris() passes the IRIs obtained from SPARQL to the IRI consumer set by the BatchProcessor. The latter
	// pushes each IRI into a batch and submits a filled-up batch to the parallel executor.
	Consumer<Consumer<QuerySolution>> relIriProcessor = 
		solProc -> rdfMgr.processRelationIris ( handler.getRelationTypesSparql (), solProc );
	
	super.process ( relIriProcessor );
	log.info ( "Cypher Relations Loading ended" );
}
 
Example #25
Source Project: xcurator   Author: xcurator   File: ExTDB_Txn1.java    License: Apache License 2.0 5 votes vote down vote up
public static void execQuery(String sparqlQueryString, Dataset dataset)
{
    Query query = QueryFactory.create(sparqlQueryString) ;
    QueryExecution qexec = QueryExecutionFactory.create(query, dataset) ;
    try {
        ResultSet results = qexec.execSelect() ;
        for ( ; results.hasNext() ; )
        {
            QuerySolution soln = results.nextSolution() ;
            int count = soln.getLiteral("count").getInt() ;
            System.out.println("count = "+count) ;
        }
      } finally { qexec.close() ; }
}
 
Example #26
Source Project: SDA   Author: iotoasis   File: OneM2MSubscribeUriMapper.java    License: 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 #27
Source Project: NLIWOD   Author: dice-group   File: QueryAnswerTypeAnalyzer.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/***
 * Queries the DBpedia SPARQL endpoint for the range of the given property.
 * @param property
 * @return range of the property
 */
private String queryRange(String property) {	
	String q = "PREFIX rdfs:   <http://www.w3.org/2000/01/rdf-schema#> SELECT ?x {<" + property + "> rdfs:range ?x.  }";	
	QueryExecution qe = QueryExecutionFactory.sparqlService(SERVICE, q);
	ResultSet rs = qe.execSelect();	
	if(rs.hasNext()) {
		QuerySolution solution = rs.nextSolution();			
		RDFNode node = solution.get("?x");	
		return node.toString();
	}	
	return "Misc";
}
 
Example #28
Source Project: NLIWOD   Author: dice-group   File: SPARQL.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Executes a select query for the given endpoint and query. Returns the answer as an {@link Results} object.
 * @param query
 * @param endpoint
 * @return
 */
public static Results executeSelect(final String query, final String endpoint) {
	QueryExecutionFactory qef = new QueryExecutionFactoryHttp(endpoint);
	QueryExecution qe = qef.createQueryExecution(query);

	ResultSet rs = qe.execSelect();	
	
	Results res = new Results();
	res.header.addAll(rs.getResultVars());

	while(rs.hasNext()) {
		QuerySolution sol = rs.nextSolution();
		res.table.add(new ArrayList<String>());
		for(String head: res.header) {
			String answer = "";
			
			if(sol.get(head).isResource()) {
				answer = sol.getResource(head).toString();
			} else {
				String temp = sol.get(head).toString();
				if(temp.contains("@")) {
					answer = "\"" + temp.substring(0, temp.indexOf("@")) + "\"" + temp.substring(temp.indexOf("@"));
				} else if (temp.contains("^^")){
					answer = "\"" + temp.substring(0, temp.indexOf("^")) + "\"^^<" + temp.substring(temp.indexOf("^")+2) + ">";
				} else {
					answer = temp;
				}
			}
			res.table.get(res.table.size()-1).add(answer);
		}
	}		
	closeExecFactory(qef);
	return res;
}
 
Example #29
Source Project: NLIWOD   Author: dice-group   File: PropertySurfaceForms.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {

		PROPERTY_SURFACE_FORMS = DIRECTORY + "property_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_PROPERTY_FILE);
		if (in == null) {
			throw new IllegalArgumentException("File: " + DBPEDIA_PROPERTY_FILE + " not found");
		}

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

		Model outputModel = ModelFactory.createDefaultModel();
		QueryExecution qExec = QueryExecutionFactory
				.create("SELECT ?s  ?label WHERE{?s a <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property>."
						+ " ?s <http://www.w3.org/2000/01/rdf-schema#label> ?label. }", inputModel);
		ResultSet rs = qExec.execSelect();
		System.out.println(qExec);
		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(PROPERTY_SURFACE_FORMS);
		RDFDataMgr.write(outputFile, outputModel, RDFFormat.NTRIPLES);
	}
 
Example #30
Source Project: NLIWOD   Author: dice-group   File: ClassSurfaceForms.java    License: 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);

	}