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

The following examples show how to use com.hp.hpl.jena.rdf.model.RDFNode. 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: micro-integrator   Source File: SparqlQueryBase.java    License: 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 Project: micro-integrator   Source File: SPARQLQuery.java    License: 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 3
Source Project: GeoTriples   Source File: WP2RDFXMLWriter.java    License: 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 4
Source Project: GeoTriples   Source File: PlainTextMessageRenderer.java    License: 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 5
Source Project: GeoTriples   Source File: Message.java    License: 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 6
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 7
Source Project: GeoTriples   Source File: D2RQWriter.java    License: 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 8
Source Project: wandora   Source File: SparqlExtractor.java    License: 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 9
Source Project: GeoTriples   Source File: RDFComparator.java    License: 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 10
Source Project: semanticMDR   Source File: ValueDomainImpl.java    License: 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 11
Source Project: LodView   Source File: OntologyBean.java    License: 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 12
Source Project: Benchmark   Source File: RDFFileManager.java    License: 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 13
Source Project: LodView   Source File: SPARQLEndPoint.java    License: 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 14
Source Project: Benchmark   Source File: RDFFileManager.java    License: 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 15
Source Project: semanticMDR   Source File: ValueDomainImpl.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public Integer getValueDomainMaximumCharacterQuantity() {
	RDFNode valueDomainMaximumCharacterQuantity = getPropertyValue(mdrDatabase
			.getVocabulary().valueDomainMaximumCharacterQuantity);
	if (valueDomainMaximumCharacterQuantity == null) {
		logger.debug("ValueDomain does not have maxiumumCharacterQuantity");
		return null;
	}
	return valueDomainMaximumCharacterQuantity.asLiteral().getInt();
}
 
Example 16
Source Project: marklogic-contentpump   Source File: RDFReader.java    License: Apache License 2.0 5 votes vote down vote up
private String object(RDFNode node) {
    if (node.isLiteral()) {
        Literal lit = node.asLiteral();
        String text = lit.getString();
        String lang = lit.getLanguage();
        String type = lit.getDatatypeURI();

        if (lang == null || "".equals(lang)) {
            lang = "";
        } else {
            lang = " xml:lang='" + escapeXml(lang) + "'";
        }

        if ("".equals(lang)) {
            if (type == null) {
                type = "http://www.w3.org/2001/XMLSchema#string";
            }
            type = " datatype='" + escapeXml(type) + "'";
        } else {
            type = "";
        }

        return "<sem:object" + type + lang + ">" + escapeXml(text) + "</sem:object>";
    } else if (node.isAnon()) {
        return "<sem:object>http://marklogic.com/semantics/blank/" + Long.toHexString(
                hash64(fuse(scramble(milliSecs),randomValue), node.toString()))
                +"</sem:object>";
    } else {
        return "<sem:object>" + escapeXml(node.toString()) + "</sem:object>";
    }
}
 
Example 17
@Override
public String getChangeDescription() {
	RDFNode changeDescription = getPropertyValue(mdrDatabase
			.getVocabulary().changeDescription);
	if (changeDescription == null) {
		logger.debug("AdministrationRecord does not have changeDescription");
		return null;
	}
	return changeDescription.asLiteral().getString();
}
 
Example 18
@Override
public String getAdministrativeNote() {
	RDFNode administrativeNote = getPropertyValue(mdrDatabase
			.getVocabulary().administrativeNote);
	if (administrativeNote == null) {
		logger.debug("AdministrationRecord does not have administrativeNote");
		return null;
	}
	return administrativeNote.asLiteral().getString();
}
 
Example 19
@Override
public Country getCountryIdentifier() {
	RDFNode countryIdentifier = getPropertyValue(mdrDatabase
			.getVocabulary().countryIdentifier);
	if (countryIdentifier == null) {
		logger.debug("LanguageIdentification does not have countryIdentifier");
		return null;
	}
	return Country.getByValue(countryIdentifier.asLiteral().getString());
}
 
Example 20
Source Project: semanticMDR   Source File: DatatypeImpl.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public String getDatatypeDescription() {
	RDFNode datatypeDescription = getPropertyValue(mdrDatabase
			.getVocabulary().datatypeDescription);
	if (datatypeDescription == null) {
		logger.debug("DataType does not have datatypeDescription");
		return null;
	}
	return datatypeDescription.asLiteral().getString();
}
 
Example 21
Source Project: xcurator   Source File: OpenCycOntology.java    License: Apache License 2.0 5 votes vote down vote up
private Set<String> getTypesOfSubject(Resource subject) {
    Set<String> ret = new HashSet<String>();

    StmtIterator stiter2
            = model.listStatements(new SimpleSelector(subject, RDF.type, (RDFNode) null));
    while (stiter2.hasNext()) {
        String uri = stiter2.next().getObject().asResource().getURI();
        if (uri.startsWith("http://sw.opencyc.org")) {
            ret.add(uri);
        }
    }

    return ret;
}
 
Example 22
Source Project: GeoTriples   Source File: PrettyTurtleWriter.java    License: Apache License 2.0 5 votes vote down vote up
public void printProperty(Property property, RDFNode term) {
	if (term == null) return;
	if (term.isResource()) {
		printPropertyTurtle(term != null, property, toTurtle(term.asResource()));
	} else {
		printPropertyTurtle(term != null, property, toTurtle(term.asLiteral()));
	}
}
 
Example 23
@Override
public String getDataElementConceptRelationshipTypeDescription() {
	RDFNode dataElementConceptRelationshipTypeDescription = getPropertyValue(mdrDatabase
			.getVocabulary().dataElementConceptRelationshipTypeDescription);
	return dataElementConceptRelationshipTypeDescription.asLiteral()
			.getString();
}
 
Example 24
Source Project: GeoTriples   Source File: PrettyTurtleWriter.java    License: Apache License 2.0 5 votes vote down vote up
private String toTurtleCompact(Map<Property, RDFNode> resource) {
	if (resource.isEmpty()) return "[]";
	StringBuilder result = new StringBuilder("[ ");
	for (Property property: resource.keySet()) {
		result.append(toTurtle(property));
		result.append(" ");
		result.append(toTurtle(resource.get(property)));
		result.append("; ");
	}
	result.append("]");
	return result.toString();
}
 
Example 25
Source Project: GeoTriples   Source File: VocabularySummarizer.java    License: Apache License 2.0 5 votes vote down vote up
public Collection<Resource> getUndefinedClasses(Model model) {
	Set<Resource> result = new HashSet<Resource>();
	StmtIterator it = model.listStatements(null, RDF.type, (RDFNode) null);
	while (it.hasNext()) {
		Statement stmt = it.nextStatement();
		if (stmt.getObject().isURIResource()
				&& stmt.getResource().getURI().startsWith(namespace)
				&& !classes.contains(stmt.getObject())) {
			result.add(stmt.getResource());
		}
	}
	return result;
}
 
Example 26
Source Project: GeoTriples   Source File: D2RQReader.java    License: Apache License 2.0 5 votes vote down vote up
private void parseTranslationTables() {
	Set<Resource> translationTableResources = new HashSet<Resource>();
	Iterator<? extends Resource> it = this.model.listIndividuals(D2RQ.TranslationTable);
	while (it.hasNext()) {
		translationTableResources.add(it.next());
	}
	StmtIterator stmts;
	stmts = this.model.listStatements(null, D2RQ.translateWith, (Resource) null);
	while (stmts.hasNext()) {
		translationTableResources.add(stmts.nextStatement().getResource());
	}
	stmts = this.model.listStatements(null, D2RQ.translation, (RDFNode) null);
	while (stmts.hasNext()) {
		translationTableResources.add(stmts.nextStatement().getSubject());
	}
	stmts = this.model.listStatements(null, D2RQ.javaClass, (RDFNode) null);
	while (stmts.hasNext()) {
		translationTableResources.add(stmts.nextStatement().getSubject());
	}
	stmts = this.model.listStatements(null, D2RQ.href, (RDFNode) null);
	while (stmts.hasNext()) {
		translationTableResources.add(stmts.nextStatement().getSubject());
	}
	it = translationTableResources.iterator();
	while (it.hasNext()) {
		Resource r = it.next();
		TranslationTable table = new TranslationTable(r);
		parseTranslationTable(table, r);
		this.mapping.addTranslationTable(table);
	}
}
 
Example 27
Source Project: GeoTriples   Source File: PrettyPrinter.java    License: Apache License 2.0 5 votes vote down vote up
public static String toString(RDFNode n) {
	if (n == null) return "null";
	if (n.isURIResource()) {
		Resource r = (Resource) n;
		return toString(r.asNode(), r.getModel());
	}
	return toString(n.asNode());
}
 
Example 28
@Override
public String getOpiSource() {
	RDFNode opiSource = getPropertyValue(mdrDatabase.getVocabulary().opiSource);
	if (opiSource == null) {
		logger.debug("RegistrationAuthorityIdentifier does not have opiSource");
		return null;
	}
	return opiSource.asLiteral().getString();
}
 
Example 29
Source Project: semanticMDR   Source File: RegistrarImpl.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public RegistrationAuthorityResource getRepresent() {
	RDFNode representedRegistrationAuthority = getPropertyResourceValue(mdrDatabase
			.getVocabulary().represents);
	if (representedRegistrationAuthority == null) {
		logger.debug("Registrar does not have Registration Authority");
		return null;
	}
	return new RegistrationAuthorityImpl(
			representedRegistrationAuthority.asResource(), mdrDatabase);
}
 
Example 30
@Override
public String getPropertyQualifier() {
	RDFNode propertyQualifier = getPropertyValue(mdrDatabase
			.getVocabulary().propertyQualifier);
	if (propertyQualifier == null) {
		logger.debug("DataElementConcept does not have an propertyQualifier");
		return null;
	}
	return propertyQualifier.asLiteral().getString();
}