com.hp.hpl.jena.rdf.model.RDFNode Java Examples

The following examples show how to use com.hp.hpl.jena.rdf.model.RDFNode. 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: WP2RDFXMLWriter.java    From GeoTriples with Apache License 2.0 6 votes vote down vote up
protected void writePredicate(Statement stmt, final PrintWriter writer) {
	final Property predicate = stmt.getPredicate();
	final RDFNode object = stmt.getObject();

	writer.print(space
			+ space
			+ "<"
			+ startElementTag(predicate.getNameSpace(),
					predicate.getLocalName()));

	if (object instanceof Resource) {
		writer.print(" ");
		writeResourceReference(((Resource) object), writer);
		writer.println("/>");
	} else {
		writeLiteral((Literal) object, writer);
		writer.println("</"
				+ endElementTag(predicate.getNameSpace(),
						predicate.getLocalName()) + ">");
	}
}
 
Example #3
Source File: SPARQLQuery.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private 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 #4
Source File: Message.java    From GeoTriples with Apache License 2.0 6 votes vote down vote up
/**
 * @param problem
 * @param subject May be null
 * @param predicates May be null
 * @param objects May be null
 */
public Message(Problem problem, Resource subject,
		Property[] predicates, RDFNode[] objects) {
	this.problem = problem;
	this.subject = subject;
	this.predicates = 
		predicates == null 
				? Collections.<Property>emptyList() 
				: Arrays.asList(predicates);
	Collections.sort(this.predicates, RDFComparator.getRDFNodeComparator());
	this.objects = 
		objects == null 
				? Collections.<RDFNode>emptyList() 
				: Arrays.asList(objects);
	Collections.sort(this.objects, RDFComparator.getRDFNodeComparator());
	this.detailCode = null;
	this.details = null;
}
 
Example #5
Source File: PlainTextMessageRenderer.java    From GeoTriples with Apache License 2.0 6 votes vote down vote up
private String nodeType(RDFNode node) {
	if (node.isURIResource()) {
		return "IRI";
	}
	if (node.isAnon()) {
		return "blank node";
	}
	if (!"".equals(node.asLiteral().getLanguage())) {
		return "language-tagged string";
	}
	if (node.asLiteral().getDatatypeURI() == null) {
		return "plain literal";
	}
	if (XSD.xstring.getURI().equals(node.asLiteral().getDatatypeURI())) {
		return "string literal";
	}
	return "non-string typed literal";
}
 
Example #6
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 #7
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 #8
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 #9
Source File: OntologyBean.java    From LodView with MIT License 6 votes vote down vote up
private String getSingleValue(String preferredLanguage, Resource IRI, String prop, String defaultValue) {
	NodeIterator iter = model.listObjectsOfProperty(IRI, model.createProperty(prop));
	String result = defaultValue;
	boolean betterTitleMatch = false;
	while (iter.hasNext()) {
		RDFNode node = iter.nextNode();
		Literal l = node.asLiteral();
		//System.out.println(IRI + " " + preferredLanguage + " --> " + l.getLanguage() + " --> " + l.getLexicalForm());
		if (!betterTitleMatch && (result.equals(defaultValue) || l.getLanguage().equals("en") || l.getLanguage().equals(preferredLanguage))) {
			if (preferredLanguage.equals(l.getLanguage())) {
				betterTitleMatch = true;
			}
			result = l.getLexicalForm();
		}

	}
	return result;
}
 
Example #10
Source File: ProcessEventObjectsStream.java    From EventCoreference with Apache License 2.0 6 votes vote down vote up
private static ResultSet getAssociatedTimes(RDFNode eventId, Model m) {
    String multiPointQuery = "SELECT ?begin ?end WHERE { { <" + eventId + ">  <http://semanticweb.cs.vu.nl/2009/11/sem/hasEarliestBeginTimeStamp> ?t1 . ?t1 <http://www.w3.org/TR/owl-time#inDateTime> ?begin . OPTIONAL { <" + eventId + ">  <http://semanticweb.cs.vu.nl/2009/11/sem/hasEarliestEndTimeStamp> ?t2 . ?t2 <http://www.w3.org/TR/owl-time#inDateTime> ?end . } } UNION ";
    multiPointQuery += "{ <" + eventId + ">  <http://semanticweb.cs.vu.nl/2009/11/sem/hasEarliestEndTimeStamp> ?t2 . ?t2 <http://www.w3.org/TR/owl-time#inDateTime> ?end . OPTIONAL { <" + eventId + ">  <http://semanticweb.cs.vu.nl/2009/11/sem/hasEarliestBeginTimeStamp> ?t1 . ?t1 <http://www.w3.org/TR/owl-time#inDateTime> ?begin . } } }";

    Query mpQuery = QueryFactory.create(multiPointQuery);

    // Create a single execution of this query, apply to a model
    // which is wrapped up as a Dataset
    QueryExecution mpQexec = QueryExecutionFactory.create(mpQuery, m);

    try {
        // Assumption: it’s a SELECT query.
        ResultSet mprs = mpQexec.execSelect();
        mpQexec.close();
        return mprs;
    } finally {

    }

}
 
Example #11
Source File: D2RQWriter.java    From GeoTriples with Apache License 2.0 6 votes vote down vote up
private void printTranslationTable(TranslationTable table) {
	printMapObject(table, D2RQ.TranslationTable);
	out.printURIProperty(D2RQ.href, table.getHref());
	out.printProperty(D2RQ.javaClass, table.getJavaClass());
	Iterator<Translation> it = table.getTranslations().iterator();
	List<Map<Property,RDFNode>> values = new ArrayList<Map<Property,RDFNode>>();
	while (it.hasNext()) {
		Translation translation = it.next();
		Map<Property,RDFNode> r = new LinkedHashMap<Property,RDFNode>();
		r.put(D2RQ.databaseValue, 
				ResourceFactory.createPlainLiteral(translation.dbValue()));
		r.put(D2RQ.rdfValue, 
				ResourceFactory.createPlainLiteral(translation.rdfValue()));
		values.add(r);
	}
	out.printCompactBlankNodeProperties(D2RQ.translation, values);
}
 
Example #12
Source File: SparqlExtractor.java    From wandora with GNU General Public License v3.0 6 votes vote down vote up
public Topic solveObjectRoleFor(Property predicate, RDFNode object, TopicMap map) {
    if(map == null) return null;
    RDF2TopicMapsMapping[] mappings = null; // getMappings();
    String predicateString = predicate.toString();
    String objectString = object.toString();
    String si = RDF2TopicMapsMapping.DEFAULT_OBJECT_ROLE_SI;
    String bn = RDF2TopicMapsMapping.DEFAULT_OBJECT_ROLE_BASENAME;
    T2<String, String> mapped = null;
    if(mappings != null) {
        for(int i=0; i<mappings.length; i++) {
            mapped = mappings[i].solveObjectRoleFor(predicateString, objectString);
            if(mapped.e1 != null && mapped.e2 != null) {
                si = mapped.e1;
                bn = mapped.e2;
                break;
            }
        }
    }
    return getOrCreateTopic(map, si, bn);
}
 
Example #13
Source File: RDFComparator.java    From GeoTriples with Apache License 2.0 6 votes vote down vote up
public int compare(RDFNode n1, RDFNode n2) {
	if (n1.isURIResource()) {
		if (!n2.isURIResource()) return -1;
		return n1.asResource().getURI().compareTo(n2.asResource().getURI());
	}
	if (n1.isAnon()) {
		if (n2.isURIResource()) return 1;
		if (n2.isLiteral()) return -1;
		return n1.asResource().getId().getLabelString().compareTo(n2.asResource().getId().getLabelString());
	}
	if (!n2.isLiteral()) return 1;
	int cmpLex = n1.asLiteral().getLexicalForm().compareTo(n2.asLiteral().getLexicalForm());
	if (cmpLex != 0) return cmpLex;
	if (n1.asLiteral().getDatatypeURI() == null) {
		if (n2.asLiteral().getDatatypeURI() != null) return -1;
		return n1.asLiteral().getLanguage().compareTo(n2.asLiteral().getLanguage());
	}
	if (n2.asLiteral().getDatatypeURI() == null) return 1;
	return n1.asLiteral().getDatatypeURI().compareTo(n2.asLiteral().getDatatypeURI()); 
}
 
Example #14
Source File: ValueDomainImpl.java    From semanticMDR with GNU General Public License v3.0 6 votes vote down vote up
@Override
public ConceptualDomainResource getRepresentingConceptualDomainRepresentation() {
	RDFNode representingConceptualDomainRepresentation = getPropertyValue(mdrDatabase
			.getVocabulary().representingConceptualDomainRepresentation);
	OntClass ontClass = representingConceptualDomainRepresentation.as(
			OntResource.class).asClass();

	ConceptualDomainResource conceptualDomainIND = null;
	if (ontClass
			.hasSuperClass(mdrDatabase.getVocabulary().EnumeratedConceptualDomain)) {
		conceptualDomainIND = new EnumeratedConceptualDomainImpl(
				representingConceptualDomainRepresentation.asResource(),
				mdrDatabase);
	}
	if (ontClass
			.hasSuperClass(mdrDatabase.getVocabulary().NonEnumeratedConceptualDomain)) {
		conceptualDomainIND = new NonEnumeratedConceptualDomainImpl(
				representingConceptualDomainRepresentation.asResource(),
				mdrDatabase);
	}
	if (conceptualDomainIND == null) {
		throw new IllegalStateException(
				"Property value should have a valid OntClass.");
	}
	return conceptualDomainIND;
}
 
Example #15
Source File: ValueMeaningImpl.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String getValueMeaningDescription() {
	RDFNode valueMeaningDescription = getPropertyValue(mdrDatabase
			.getVocabulary().valueMeaningDescription);
	if (valueMeaningDescription == null) {
		logger.debug("ValueMeaning does not have description");
		return null;
	}
	return valueMeaningDescription.asLiteral().getString();
}
 
Example #16
Source File: AdministrationRecordImpl.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Calendar getUntilDate() {
	RDFNode untilDate = getPropertyValue(mdrDatabase.getVocabulary().untilDate);
	if (untilDate == null) {
		logger.debug("AdministrationRecord does not have untilDate");
		return null;
	}
	return DatatypeConverter.parseDateTime(untilDate.asLiteral()
			.getLexicalForm());
}
 
Example #17
Source File: ConfigurationBean.java    From LodView with MIT License 5 votes vote down vote up
private List<String> getMultiConfValue(String prop) {
	List<String> result = new ArrayList<String>();
	NodeIterator iter = confModel.listObjectsOfProperty(confModel.createProperty(confModel.getNsPrefixURI("conf"), prop));
	while (iter.hasNext()) {
		RDFNode node = iter.next();
		result.add(node.toString());
	}
	return result;
}
 
Example #18
Source File: PermissibleValueImpl.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Calendar getPermissibleValueBeginDate() {
	RDFNode permissibleValueBeginDate = getPropertyValue(mdrDatabase
			.getVocabulary().permissibleValueBeginDate);
	return DatatypeConverter.parseDateTime(permissibleValueBeginDate
			.asLiteral().getLexicalForm());
}
 
Example #19
Source File: R2RMLReader.java    From GeoTriples with Apache License 2.0 5 votes vote down vote up
public RDFNode getRDFNode(Resource r, Property p, NodeType acceptableNodes) {
	List<RDFNode> all = getRDFNodes(r, p, acceptableNodes);
	if (all.isEmpty()) return null;
	if (all.size() > 1) {
		report.report(Problem.DUPLICATE_VALUE, r, p, all.toArray(new RDFNode[all.size()]));
	}
	return all.iterator().next();
}
 
Example #20
Source File: ValueDomainImpl.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
@Override
public UnitOfMeasureResource getValueDomainUnitOfMeasure() {
	RDFNode valueDomainUnitOfMeasure = getPropertyValue(mdrDatabase
			.getVocabulary().valueDomainUnitOfMeasure);
	if (valueDomainUnitOfMeasure == null) {
		logger.debug("ValueDomain does not have UnitOfMeasure");
		return null;
	}
	return new UnitOfMeasureImpl(valueDomainUnitOfMeasure.asResource(),
			mdrDatabase);
}
 
Example #21
Source File: R2RMLReader.java    From GeoTriples with Apache License 2.0 5 votes vote down vote up
private void checkForSpuriousTypes() {
	// This doesn't catch spurious subclass triples, e.g., rr:SubjectMap,
	// rr:R2RMLView.
	for (ComponentType type: ComponentType.values()) {
		ResIterator it = model.listResourcesWithProperty(RDF.type, type.asResource());
		while (it.hasNext()) {
			Resource r = it.next();
			if (mapping.getMappingComponent(r, type) == null) {
				report.report(Problem.SPURIOUS_TYPE, r, RDF.type, type.asResource());
			}
		}
	}
	remainingTriples.removeAll(null, RDF.type, (RDFNode) null);
}
 
Example #22
Source File: AdministrationRecordImpl.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String getUnresolvedIssue() {
	RDFNode unresolvedIssue = getPropertyValue(mdrDatabase.getVocabulary().unresolvedIssue);
	if (unresolvedIssue == null) {
		logger.debug("AdministrationRecord does not have unresolvedIssue");
		return null;
	}
	return unresolvedIssue.asLiteral().getString();
}
 
Example #23
Source File: R2RMLReader.java    From GeoTriples with Apache License 2.0 5 votes vote down vote up
private void readTermMap(TermMap termMap, Resource r) {
	termMap.getGraphMaps().addAll(getResources(r, RR.graphMap));
	for (RDFNode graph: getRDFNodes(r, RR.graph)) {
		termMap.getGraphs().add(ConstantShortcut.create(graph));
	}
	for (RDFNode class_: getRDFNodes(r, RR.class_, NodeType.IRI)) {
		termMap.getClasses().add(ConstantIRI.create(class_.asResource()));
	}
	checkTermMapType(r, RR.SubjectMap, RR.subjectMap);
	checkTermMapType(r, RR.PredicateMap, RR.predicateMap);
	checkTermMapType(r, RR.ObjectMap, RR.objectMap);
	checkTermMapType(r, RR.GraphMap, RR.graphMap);
}
 
Example #24
Source File: DataElementImpl.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Integer getDataElementPrecision() {
	RDFNode dataElementPrecision = getPropertyValue(mdrDatabase
			.getVocabulary().dataElementPrecision);
	if (dataElementPrecision == null) {
		logger.debug("DataElement does not have dataElementPrecision");
		return null;
	}
	return dataElementPrecision.asLiteral().getInt();
}
 
Example #25
Source File: Misc.java    From LodView with MIT License 5 votes vote down vote up
private static Integer countFathers(String value, int i, Model model) {
	NodeIterator iter = model.listObjectsOfProperty(model.createResource(value), model.createProperty("http://www.w3.org/2000/01/rdf-schema#subClassOf"));
	while (iter.hasNext()) {
		RDFNode node = iter.next();
		return countFathers(node.toString(), ++i, model);
	}
	return i;
}
 
Example #26
Source File: ClassificationSchemeItemImpl.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String getClassificationSchemeItemValue() {
	RDFNode classificationSchemeItemValue = getPropertyValue(mdrDatabase
			.getVocabulary().classificationSchemeItemValue);
	if (classificationSchemeItemValue == null) {
		logger.debug("ClassificationSchemeItem does not have classificationSchemeItemValue");
		return null;
	}
	return classificationSchemeItemValue.asLiteral().getString();
}
 
Example #27
Source File: Util.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
public <T extends MDRResource> List<T> createList(ExtendedIterator<? extends RDFNode> it,
		Class<T> cls) throws MDRException {

	List<T> newList = new ArrayList<T>();
	try {
		Transformer transformer = transformerMap.get(cls);
		CollectionUtils.collect(it, transformer, newList);
	} catch (Exception e) {
		throw new MDRException(e);
	}
	return newList;
}
 
Example #28
Source File: ReferenceDocumentImpl.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String getReferenceDocumentTypeDescription() {
	RDFNode referenceDocumentTypeDescription = getPropertyValue(mdrDatabase
			.getVocabulary().referenceDocumentTypeDescription);
	if (referenceDocumentTypeDescription == null) {
		logger.debug("ReferenceDocument does not have referenceDocumentTypeDescription");
		return null;
	}
	return referenceDocumentTypeDescription.asLiteral().getString();
}
 
Example #29
Source File: R2RMLReader.java    From GeoTriples with Apache License 2.0 5 votes vote down vote up
public RDFNode coerce(RDFNode in) {
	if (in.isAnon()) return null;
	if (in.isURIResource()) {
		return ResourceFactory.createPlainLiteral(in.asResource().getURI());
	}
	return ResourceFactory.createPlainLiteral(in.asLiteral().getLexicalForm());
}
 
Example #30
Source File: QueryHelper.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
public Resource resource(String binding) {
	if(!this.solution.contains(binding)) {
		return null;
	}
	RDFNode node = this.solution.get(binding);
	if(!node.canAs(Resource.class)) {
		throw new IllegalStateException("Binding '"+binding+"' is not a resource");
	}
	return node.asResource();
}