Java Code Examples for com.hp.hpl.jena.query.QuerySolution#get()

The following examples show how to use com.hp.hpl.jena.query.QuerySolution#get() . 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: SparqlQueryBase.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
public DataEntry getDataEntryFromRS(ResultSet rs) {
	DataEntry dataEntry = new DataEntry();
	QuerySolution soln = rs.nextSolution();
	String colName, value;
	boolean useColumnNumbers = this.isUsingColumnNumbers();
	/* for each column get the colName and colValue and add to the data entry */
	for (int i = 0; i < rs.getResultVars().size(); i++) {
		colName = rs.getResultVars().get(i);
		RDFNode node = soln.get(colName) ;  			
		if (node.isLiteral()) {
			value = convertRSToString(soln, colName);
		} else {
			value = soln.getResource(colName).getURI();
		}			
		dataEntry.addValue(useColumnNumbers ? Integer.toString(i + 1) : 
			colName, new ParamValue(value));
	}
	return dataEntry;
}
 
Example 2
Source File: RDFFileManager.java    From Benchmark with GNU General Public License v3.0 6 votes vote down vote up
private static Map<String, EventDeclaration> extractEDsFromDataset(Dataset dataset) {
	// List<EventDeclaration> eds = new ArrayList<EventDeclaration>();
	String describeStr = queryPrefix
			+ " select ?x"
			+ " where{?x rdf:type ?y graph <http://www.insight-centre.org/ces#> { ?y rdfs:subClassOf ces:EventService}}";
	// Query query = QueryFactory.create(describeStr);
	// query.setPrefixMapping(pmap);
	QueryExecution qe = QueryExecutionFactory.create(describeStr, dataset);
	ResultSet results = qe.execSelect();
	// ResultSetFormatter.out(System.out, results, query);
	Map<String, EventDeclaration> edMap = new HashMap<String, EventDeclaration>();
	while (results.hasNext()) {
		QuerySolution row = results.next();
		RDFNode edID = row.get("x");
		// System.out.println("has id: " + edID.toString());
		extractEDByServiceID(edID, dataset, edMap);
	}
	// RDFDataMgr.write(System.out, results, Lang.TURTLE);
	return edMap;
}
 
Example 3
Source File: RDFFileManager.java    From Benchmark with GNU General Public License v3.0 6 votes vote down vote up
private static String extractEventPayloads(EventDeclaration ed, Dataset dataset) {
	String queryStr = queryPrefix + " select ?x ?y ?z where {<" + ed.getnodeId()
			+ "> ssn:observes ?x. ?x rdf:type ?y. ?x ssn:isPropertyOf ?z }";
	QueryExecution qe = QueryExecutionFactory.create(queryStr, dataset);
	ResultSet results = qe.execSelect();
	List<String> payloads = new ArrayList<String>();
	String foiId = "";
	while (results.hasNext()) {
		QuerySolution result = results.next();
		RDFNode propertyName = result.get("x");
		RDFNode propertyType = result.get("y");
		RDFNode foi = result.get("z");
		if (propertyType.toString().equals("http://www.w3.org/2000/01/rdf-schema#Resource"))
			continue;
		// System.out.println("type: " + property + " foi: " + foi);
		payloads.add(propertyType.toString() + "|" + foi.toString() + "|" + propertyName.toString());
		foiId = foi.toString();
		// System.out.println("payload: " + propertyType.toString() + "|" + foi.toString() + "|"
		// + propertyName.toString());
	}
	ed.setPayloads(payloads);
	return foiId;
}
 
Example 4
Source File: RDFFileManager.java    From Benchmark with GNU General Public License v3.0 6 votes vote down vote up
public static EventPattern extractQueryFromDataset(String serviceRequest) {
	Model queryBase = FileManager.get().loadModel(datasetDirectory + serviceRequest);
	dataset.getDefaultModel().add(ModelFactory.createOntologyModel(ontoSpec, queryBase));

	String describeStr = queryPrefix + " select ?x  where{?x rdf:type ces:EventRequest}";
	// Query query = QueryFactory.create(describeStr);
	// query.setPrefixMapping(pmap);
	QueryExecution qe = QueryExecutionFactory.create(describeStr, dataset);
	ResultSet results = qe.execSelect();
	// ResultSetFormatter.out(System.out, results, query);
	Map<String, EventDeclaration> edMap = new HashMap<String, EventDeclaration>();
	EventPattern ep = new EventPattern();
	ep.setQuery(true);
	while (results.hasNext()) {
		// System.out.println("results!");
		QuerySolution row = results.next();
		RDFNode edID = row.get("x");
		// System.out.println("has id: " + edID.toString());
		ep = extractEDByServiceID(edID, dataset, edMap).getEp();
	}
	return ep;
}
 
Example 5
Source File: RDFFileManager.java    From Benchmark with GNU General Public License v3.0 6 votes vote down vote up
public static EventPattern extractCompositionPlanFromDataset(String serviceRequest) {
	Model queryBase = FileManager.get().loadModel(datasetDirectory + serviceRequest);
	dataset.getDefaultModel().add(ModelFactory.createOntologyModel(ontoSpec, queryBase));

	String describeStr = queryPrefix + " select ?x  where{?x rdf:type ces:CompositionPlan}";
	// Query query = QueryFactory.create(describeStr);
	// query.setPrefixMapping(pmap);
	QueryExecution qe = QueryExecutionFactory.create(describeStr, dataset);
	ResultSet results = qe.execSelect();
	// ResultSetFormatter.out(System.out, results, query);
	Map<String, EventDeclaration> edMap = new HashMap<String, EventDeclaration>();
	EventPattern ep = new EventPattern();
	ep.setQuery(false);
	while (results.hasNext()) {
		// System.out.println("results!");
		QuerySolution row = results.next();
		RDFNode edID = row.get("x");
		// System.out.println("has id: " + edID.toString());
		ep = extractEDByServiceID(edID, dataset, edMap).getEp();
	}
	return ep;
}
 
Example 6
Source File: RDFFileManager.java    From Benchmark with GNU General Public License v3.0 6 votes vote down vote up
public static EventPattern extractQueryFromModel(Model serviceRequest) {
	// Model queryBase = FileManager.get().loadModel(datasetDirectory + serviceRequest);
	dataset.getDefaultModel().add(ModelFactory.createOntologyModel(ontoSpec, serviceRequest));

	String describeStr = queryPrefix + " select ?x  where{?x rdf:type ces:EventRequest}";
	// Query query = QueryFactory.create(describeStr);
	// query.setPrefixMapping(pmap);
	QueryExecution qe = QueryExecutionFactory.create(describeStr, dataset);
	ResultSet results = qe.execSelect();
	// ResultSetFormatter.out(System.out, results, query);
	Map<String, EventDeclaration> edMap = new HashMap<String, EventDeclaration>();
	EventPattern ep = new EventPattern();

	while (results.hasNext()) {
		// System.out.println("results!");
		QuerySolution row = results.next();
		RDFNode edID = row.get("x");
		// System.out.println("has id: " + edID.toString());
		ep = extractEDByServiceID(edID, dataset, edMap).getEp();
	}
	return ep;
}
 
Example 7
Source File: Entity.java    From xcurator with Apache License 2.0 6 votes vote down vote up
private Object getSameResource(Model model, String typePrefix,
        Element item, Document dataDoc) throws XPathExpressionException {
    QueryExecution qExec = null;
    try {
        String query = getEqualsQuery(model, typePrefix, item, dataDoc);
        LogUtils.debug(this.getClass(), query);
        qExec = QueryExecutionFactory.create(query, model);
        ResultSet rs = qExec.execSelect();
        while (rs.hasNext()) {
            QuerySolution solution = rs.next();
            return solution.get("?x0");
        }
    } catch (Exception e) {
        if (debug) {
            e.printStackTrace();
        }
    } finally {
        if (qExec != null) {
            qExec.close();
        }
    }
    return null;
}
 
Example 8
Source File: SPARQLEndPoint.java    From LodView with MIT License 6 votes vote down vote up
public Model extractLocalData(Model result, String IRI, Model m, List<String> queries) throws Exception {

		// System.out.println("executing query on IRI");
		Resource subject = result.createResource(IRI);
		for (String query : queries) {
			QueryExecution qe = QueryExecutionFactory.create(parseQuery(query, IRI, null, -1, null), m);
			try {
				ResultSet rs = qe.execSelect();
				List<Statement> sl = new ArrayList<Statement>();
				while (rs.hasNext()) {
					QuerySolution qs = rs.next();
					RDFNode subject2 = qs.get("s");
					RDFNode property = qs.get("p");
					RDFNode object = qs.get("o");
					result.add(result.createStatement(subject2 != null ? subject2.asResource() : subject, property.as(Property.class), object));
				}
				result.add(sl);
			} catch (Exception e) {
				e.printStackTrace();
				throw new Exception("error in query execution: " + e.getMessage());
			} finally {
				qe.close();
			}
		}
		return result;
	}
 
Example 9
Source File: TrigKSTripleReader.java    From EventCoreference with Apache License 2.0 6 votes vote down vote up
public static ArrayList<Statement> readTriplesFromKs(String subjectUri, String sparqlQuery){

        ArrayList<Statement> triples = new ArrayList<Statement>();
        HttpAuthenticator authenticator = new SimpleAuthenticator(user, pass.toCharArray());
        try {
            qCount++;
            QueryExecution x = QueryExecutionFactory.sparqlService(serviceEndpoint, sparqlQuery, authenticator);
            ResultSet resultset = x.execSelect();
            while (resultset.hasNext()) {
                QuerySolution solution = resultset.nextSolution();
                String relString = solution.get("predicate").toString();
                RDFNode obj = solution.get("object");
                Model model = ModelFactory.createDefaultModel();
                Resource subj = model.createResource(subjectUri);
                Statement s = createStatement(subj, ResourceFactory.createProperty(relString), obj);
                triples.add(s);
            }
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return triples;
    }
 
Example 10
Source File: SPARQLEndPoint.java    From LodView with MIT License 5 votes vote down vote up
public Model extractData(Model result, String IRI, String sparql, List<String> queries) throws Exception {

		// System.out.println("executing query on " + sparql);
		Resource subject = result.createResource(IRI);
		for (String query : queries) {
			QueryExecution qe = QueryExecutionFactory.sparqlService(sparql, parseQuery(query, IRI, null, -1, null));
			try {
				ResultSet rs = qe.execSelect();

				List<Statement> sl = new ArrayList<Statement>();
				while (rs.hasNext()) {
					QuerySolution qs = rs.next();
					RDFNode subject2 = qs.get("s");
					RDFNode property = qs.get("p");
					RDFNode object = qs.get("o");
					result.add(result.createStatement(subject2 != null ? subject2.asResource() : subject, property.as(Property.class), object));
				}
				result.add(sl);
			} catch (Exception e) {
				e.printStackTrace();
				throw new Exception("error in query execution: " + e.getMessage());
			} finally {
				qe.close();
			}
		}
		return result;
	}
 
Example 11
Source File: RDFFileManager.java    From Benchmark with GNU General Public License v3.0 4 votes vote down vote up
private static void extractEventQoS(EventDeclaration ed, Dataset dataset) {
	// TODO change quality prefix

	String queryStr = queryPrefix
			+ " select  ?type ?value where {<"
			+ ed.getnodeId()
			+ "> owls:presents ?profile. ?profile ?hasnfp ?x. ?x rdf:type ?type. ?x owlssp:sParameter ?y. ?y emvo:hasQuantityValue ?value "
			+ " graph <http://www.insight-centre.org/ces#> {?hasnfp rdfs:subPropertyOf owlssp:serviceParameter}}";

	// String queryStr = queryPrefix
	// +
	// " select ?srvId ?type ?value where {?srvId owls:presents ?profile. ?profile ?hasnfp ?x. ?x rdf:type ?type. ?x owlssp:sParameter ?y. ?y emvo:hasQuantityValue ?value }";
	long t1 = System.currentTimeMillis();
	// String queryStr = queryPrefix
	// + "select ?srvId ?srvCatName ?pType ?foiId ?a ?b ?c ?d ?qType ?qValue where { "
	// +
	// "?srvId owls:presents ?profile. ?profile owlssc:serviceCategory ?srvCat. ?srvCat owlssc:serviceCategoryName "
	// + "?srvCatName. ?srvId ssn:observes ?pid. ?pid rdf:type ?pType. ?pid ssn:isPropertyOf ?foiId. "
	// + "?foiId ct:hasStartLatitude ?a. ?foiId ct:hasStartLongitude ?b. ?foiId ct:hasEndLatitude ?c. "
	// + "?foiId ct:hasEndLongitude ?d. OPTIONAL {?srvId owls:presents ?profile.  ?profile ?hasnfp ?x.  "
	// + "?x rdf:type ?qType.  ?x owlssp:sParameter ?y.  ?y emvo:hasQuantityValue ?qValue "
	// + "graph <http://www.insight-centre.org/ces#> {?hasnfp rdfs:subPropertyOf ces:hasNFP}}}";
	QueryExecution qe = QueryExecutionFactory.create(queryStr, dataset);
	ResultSet results = qe.execSelect();
	QosVector qos = new QosVector();
	boolean hasQos = false;
	int sum = 0;
	while (results.hasNext()) {
		sum++;
		hasQos = true;
		QuerySolution row = results.next();
		RDFNode type = row.get("type");
		RDFNode value = row.get("value");
		// type.
		// ed.setSrc(addr.toString());
		// System.out.println("type: " + type + "\n value: " + value);
		if (type.toString().equals("http://www.insight-centre.org/ces#Security"))
			qos.setSecurity(value.asLiteral().getInt());
		else if (type.toString().equals("http://www.insight-centre.org/ces#Price"))
			qos.setPrice(value.asLiteral().getInt());
		else if (type.toString().equals("http://www.insight-centre.org/ces#Accuracy"))
			qos.setAccuracy(value.asLiteral().getDouble());
		else if (type.toString().equals("http://www.insight-centre.org/ces#Reliability"))
			qos.setReliability(value.asLiteral().getDouble());
		else if (type.toString().equals("http://www.insight-centre.org/ces#Latency"))
			qos.setLatency(value.asLiteral().getInt());
		else if (type.toString().equals("http://www.insight-centre.org/ces#BandWidthConsumption"))
			;
		else if (type.toString().equals("http://www.insight-centre.org/ces#Availability"))
			;
		else if (type.toString().equals("http://www.insight-centre.org/ces#EnergyConsumption"))
			;
		else if (type.toString().equals("http://www.insight-centre.org/ces#Frequency"))
			ed.setFrequency(value.asLiteral().getDouble());
	}
	long t2 = System.currentTimeMillis();
	// logger.info("QoS extracted: " + qos);
	if (qos.getAccuracy() != null)
		ed.setInternalQos(qos);

}
 
Example 12
Source File: DBPediaCandidateType.java    From uncc2014watsonsim with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Find the possible lexical types of a name.
 * tag("New York") for example might be:
 *  {"populated place", "place", "municipality"}..
 */
public List<String> viaDBPedia(String text) {
	/*
	 * ABOUT THE QUERY
	 * ===============
	 * Most of these results are not really excellent.
	 * The recall is pretty high but the precision is low because it
	 * matches every name that _contains_ the candidate answer.
	 * 
	 * So, we should probably trim the results to the most popular names.
	 * 
	 * BUT many queries have thousands of names so this will probably be
	 * slow. Meaning we probably need to compromise or develop our own
	 * solution.
	 * 
	 * ABOUT THE RESULTS
	 * =================
	 * A lot of the results are generic, like "place". And "city" is also
	 * a place, so it may just be inadequately tagged. We probably need
	 * some graph algorithm to help with this.
	 * Some results have synonyms. "country" is a real tag, but "nation" is
	 * not. WordNet can help with this.
	 * 
	 */

	rdf.begin(ReadWrite.READ);
	List<String> types = new ArrayList<>();
	try (QueryExecution qe = QueryExecutionFactory.create(getQuery(text), 
			rdf.getDefaultModel())) {
		ResultSet rs = qe.execSelect();
		while (rs.hasNext()) {
			QuerySolution s = rs.next();
			RDFNode node = s.get("?kind");
			if (node == null) {}
			else if (node.isLiteral())
				types.add(node.asLiteral().getLexicalForm().toLowerCase());
			else if (node.isResource())
				types.add(node.asResource().getLocalName().toLowerCase());
		}
	} finally {
		rdf.end();
	}

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

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

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

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

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

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

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

        j++;
    }

    whereClause += "} ";

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

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

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

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

    //    for (Property lookupProperty: foreignLookupKey.getProperties()) {
    //      String localValue = XMLUtils.getStringByPath(lookupProperty.getPath(), item, dataDoc);
    //      Selector selector = new SimpleSelector(null, lookupProperty.getJenaProperty(model), localValue);
    //      StmtIterator iter = model.listStatements(selector);
    //
    //      while (iter.hasNext()) {
    //        Statement stmt = iter.next();
    //        if (targetEntity.equals(stmt.getSubject().getProperty(RDF.type).getObject().toString())) {
    //          parentResouce.addProperty(getJenaProperty(model), stmt.getSubject());
    //        }
    //      }
    //    }
    //
    //
    //    for (Property lookupProperty: foreignLookupKey.getProperties()) {
    //      String localValue = XMLUtils.getStringByPath(lookupProperty.getPath(), item, dataDoc);
    //      Selector selector = new SimpleSelector(null, lookupProperty.getJenaProperty(model), localValue);
    //      StmtIterator iter = model.listStatements(selector);
    //
    //      while (iter.hasNext()) {
    //        Statement stmt = iter.next();
    //        if (targetEntity.equals(stmt.getSubject().getProperty(RDF.type).getObject().toString())) {
    //          parentResouce.addProperty(getJenaProperty(model), stmt.getSubject());
    //        }
    //      }
    //    }
}
 
Example 14
Source File: SPARQLEndPoint.java    From LodView with MIT License 4 votes vote down vote up
private List<TripleBean> moreThenOneQuery(QueryExecution qe, List<TripleBean> results, int retry, String overrideProperty) throws Exception {

		try {
			ResultSet rs = qe.execSelect();
			while (rs.hasNext()) {
				TripleBean rb = new TripleBean();
				QuerySolution qs = rs.next();
				String property = "";
				if (overrideProperty != null) {
					property = overrideProperty;
				} else if (qs.get("p") != null) {
					property = qs.get("p").asNode().toString();
				}

				try {
					if (qs.get("s") != null && !qs.get("s").asNode().toString().startsWith("http://")) { // probably
																											// a
																											// bn
						rb.setIRI(qs.get("s").asNode().toString());
						rb.setNsIRI("_:" + rb.getIRI());
					} else if (qs.get("s") != null && qs.get("s").asNode().toString().startsWith("http://")) {
						rb.setIRI(qs.get("s").asNode().toString());
						rb.setNsIRI(Misc.toNsResource(rb.getIRI(), conf));
						rb.setUrl(Misc.toBrowsableUrl(rb.getIRI(), conf));
					}

					PropertyBean p = new PropertyBean();
					p.setNsProperty(Misc.toNsResource(property, conf));
					p.setProperty(property);
					if (ontoBean != null) {
						p.setLabel(ontoBean.getEscapedValue("label", locale, property));
						p.setComment(ontoBean.getEscapedValue("comment", locale, property));
					}
					p.setPropertyUrl(Misc.toBrowsableUrl(property, conf));
					rb.setProperty(p);
					if (qs.get("o") != null) {
						Node object = qs.get("o").asNode();
						if (object.isURI()) {
							rb.setType("iri");
							rb.setValue(object.toString(false));
						} else if (object.isLiteral()) {
							rb.setType("literal");
							rb.setDataType(object.getLiteralDatatypeURI());
							rb.setNsDataType(Misc.toNsResource(object.getLiteralDatatypeURI(), conf));
							rb.setLang(object.getLiteralLanguage());
							rb.setValue(object.getLiteralLexicalForm());
						} else if (object.isBlank()) {
							rb.setType("bnode");
							rb.setValue(object.toString(false));
						}
					} else {
						rb.setType("literal");
						rb.setValue("");
					}
					results.add(rb);
				} catch (Exception e) {
					System.err.println("error? " + e.getMessage());
					// e.printStackTrace();
				}
			}
		} catch (Exception ez) {
			if (retry < 3) {
				retry++;
				// System.out.println("query failed (" + ez.getMessage() +
				// "), I'm giving another chance (" + retry + "/3)");
				return moreThenOneQuery(qe, results, retry, overrideProperty);
			}
			ez.printStackTrace();
			throw new Exception("connection refused");
		}

		return results;
	}