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

The following examples show how to use com.hp.hpl.jena.rdf.model.Literal. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: anno4j   Source File: JenaSesameUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convert the given Jena Literal to a Sesame Literal
 * @param theLiteral the Jena Literal to convert
 * @return the Jena Literal as a Sesame Literal
 */
public static org.openrdf.model.Literal asSesameLiteral(Literal theLiteral) {
    if (theLiteral == null) {
        return null;
    }
    else if (theLiteral.getLanguage() != null && !theLiteral.getLanguage().equals("")) {
        return FACTORY.createLiteral(theLiteral.getLexicalForm(),
                theLiteral.getLanguage());
    }
    else if (theLiteral.getDatatypeURI() != null) {
        return FACTORY.createLiteral(theLiteral.getLexicalForm(),
                FACTORY.createURI(theLiteral.getDatatypeURI()));
    }
    else {
        return FACTORY.createLiteral(theLiteral.getLexicalForm());
    }
}
 
Example 2
Source Project: anno4j   Source File: JenaSesameUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convert a Sesame Literal to a Jena Literal
 * @param theLiteral the Sesame literal
 * @return the sesame literal converted to Jena
 */
public static com.hp.hpl.jena.rdf.model.Literal asJenaLiteral(org.openrdf.model.Literal theLiteral) {
    if (theLiteral == null) {
        return null;
    }
    else if (theLiteral.getLanguage() != null) {
        return mInternalModel.createLiteral(theLiteral.getLabel(),
                theLiteral.getLanguage());
    }
    else if (theLiteral.getDatatype() != null) {
        return mInternalModel.createTypedLiteral(theLiteral.getLabel(),
                theLiteral.getDatatype().toString());
    }
    else {
        return mInternalModel.createLiteral(theLiteral.getLabel());
    }
}
 
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: WP2RDFXMLWriter.java    License: Apache License 2.0 6 votes vote down vote up
protected void writeLiteral(Literal l, PrintWriter writer) {
	String lang = l.getLanguage();
	String form = l.getLexicalForm();
	if (!lang.equals("")) {
		writer.print(" xml:lang=" + attributeQuoted(lang));
	}
	if (l.isWellFormedXML() && !blockLiterals) {
		writer.print(" " + rdfAt("parseType") + "="
				+ attributeQuoted("Literal") + ">");
		writer.print(form);
	} else {
		String dt = l.getDatatypeURI();
		if (dt != null)
			writer.print(" " + rdfAt("datatype") + "="
					+ substitutedAttribute(dt));
		writer.print(">");
		writer.print(Util.substituteEntitiesInElementContent(form));
	}
}
 
Example 5
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 6
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 7
Source Project: anno4j   Source File: JenaSesameUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Convert the given Jena node as a Sesame Value
 * @param theNode the Jena node to convert
 * @return the jena node as a Sesame Value
 */
public static Value asSesameValue(RDFNode theNode) {
    if (theNode == null) {
        return null;
    }
    else if (theNode.canAs(Literal.class)) {
        return asSesameLiteral(theNode.as(Literal.class));
    }
    else {
        return asSesameResource(theNode.as(Resource.class));
    }
}
 
Example 8
Source Project: anno4j   Source File: JenaSesameUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Convert the sesame value to a Jena Node
 * @param theValue the Sesame value
 * @return the sesame value as a Jena node
 */
public static RDFNode asJenaNode(Value theValue) {
    if (theValue instanceof org.openrdf.model.Literal) {
        return asJenaLiteral( (org.openrdf.model.Literal) theValue);
    }
    else {
        return asJenaResource( (org.openrdf.model.Resource) theValue);
    }
}
 
Example 9
Source Project: GeoTriples   Source File: Mapping.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Helper method to add definitions from a ResourceMap to its underlying resource
 * @param map
 * @param targetResource
 */
private void addDefinitions(ResourceMap map, Resource targetResource) {
	/* Infer rdfs:Class or rdf:Property type */
	Statement s = vocabularyModel.createStatement(targetResource, RDF.type, map instanceof ClassMap ? RDFS.Class : RDF.Property);
	if (!this.vocabularyModel.contains(s))
		this.vocabularyModel.add(s);

	/* Apply labels */
	for (Literal propertyLabel: map.getDefinitionLabels()) {
		s = vocabularyModel.createStatement(targetResource, RDFS.label, propertyLabel);
		if (!this.vocabularyModel.contains(s))
			this.vocabularyModel.add(s);
	}

	/* Apply comments */
	for (Literal propertyComment: map.getDefinitionComments()) {
		s = vocabularyModel.createStatement(targetResource, RDFS.comment, propertyComment);
		if (!this.vocabularyModel.contains(s))
			this.vocabularyModel.add(s);
	}

	/* Apply additional properties */
	for (Resource additionalProperty: map.getAdditionalDefinitionProperties()) {
		s = vocabularyModel.createStatement(targetResource, 
					(Property)(additionalProperty.getProperty(D2RQ.propertyName).getResource().as(Property.class)),
					additionalProperty.getProperty(D2RQ.propertyValue).getObject());
		if (!this.vocabularyModel.contains(s))
			this.vocabularyModel.add(s);				
	}
}
 
Example 10
Source Project: Benchmark   Source File: RDFFileManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static String extractEventType(String edID, Dataset dataset) {
	String queryStr = queryPrefix + " select  ?name where {<" + edID
			+ "> owls:presents ?profile. ?profile owlssc:serviceCategory ?z. ?z owlssc:serviceCategoryName ?name}";
	QueryExecution qe = QueryExecutionFactory.create(queryStr, dataset);
	ResultSet results = qe.execSelect();
	String type = "";
	if (results.hasNext()) {
		Literal l = results.next().getLiteral("name");
		type = l.getString();
	}
	return type;
}
 
Example 11
Source Project: semweb4j   Source File: ModelImplJena.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void addStatement(org.ontoware.rdf2go.model.node.Resource subject, URI predicate,
        org.ontoware.rdf2go.model.node.Node object) throws ModelRuntimeException {
	assertModel();
	try {
		log.debug("adding a statement (" + subject + "," + predicate + "," + object + ")");
		this.modificationCount++;
		if(!(object instanceof DatatypeLiteral)) {
			this.jenaModel.getGraph().add(
			        new Triple(TypeConversion.toJenaNode(subject, this.jenaModel),
			                TypeConversion.toJenaNode(predicate, this.jenaModel),
			                TypeConversion.toJenaNode(object, this.jenaModel)));
		} else
		// DatatypeLiteral
		{
			// build Resources/Literals
			Resource s = null;
			if(subject instanceof URI) {
				s = this.jenaModel.createResource(subject.toString());
			} else
			// subject is a BlankNode
			{
				s = this.jenaModel.createResource(((Node)((AbstractBlankNodeImpl)subject)
				        .getUnderlyingBlankNode()).getBlankNodeId());
			}
			
			Property p = this.jenaModel.createProperty(predicate.toString());
			
			String datatypeValue = ((DatatypeLiteral)object).getValue();
			String datatypeURI = ((DatatypeLiteral)object).getDatatype().toString();
			Literal o = this.jenaModel.createTypedLiteral(datatypeValue, datatypeURI);
			
			// Add the statement to the model
			this.jenaModel.add(s, p, o);
		}
	} catch(BadURIException e) {
		throw new ModelRuntimeException(e);
	}
}
 
Example 12
Source Project: ldp4j   Source File: QueryHelper.java    License: Apache License 2.0 5 votes vote down vote up
public final Literal literal(String binding) {
	if(!this.solution.contains(binding)) {
		return null;
	}
	RDFNode node = this.solution.get(binding);
	if(!node.canAs(Literal.class)) {
		throw new IllegalStateException("Binding '"+binding+"' is not a literal");
	}
	return node.asLiteral();
}
 
Example 13
Source Project: r2rml-parser   Source File: LocalResource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a literal resource
 */
public LocalResource(Literal l) {
	this.literal = Boolean.TRUE;

	this.localName = l.getLexicalForm();
	//System.out.println("f from l" + localName);
}
 
Example 14
Source Project: r2rml-parser   Source File: Template.java    License: Apache License 2.0 5 votes vote down vote up
public Template(Literal literal, TermType termType, String namespace, Model model) {
	this.text = literal.getString();
	this.language = literal.getLanguage();
	this.fields = createTemplateFields();
	this.termType = termType;
	this.namespace = namespace;
	this.model = model;
}
 
Example 15
Source Project: TripleGeo   Source File: RdbToRdf.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * 
 * Insert a triple for the 'name' attribute of a feature
 */
private void insertResourceNameLiteral(String s, String p, String o, String lang) 
{
 	Resource resource = model.createResource(s);
   Property property = model.createProperty(p);
   if (lang != null) {
     Literal literal = model.createLiteral(o, lang);
     resource.addLiteral(property, literal);
   } else {
     resource.addProperty(property, o);
   }
 }
 
Example 16
Source Project: TripleGeo   Source File: RdbToRdf.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * 
 * Insert a triple for a literal value
 */
private void insertLiteralTriplet(String s, String p, String o, String x) 
{
  Resource resourceGeometry = model.createResource(s);
  Property property = model.createProperty(p);
  if (x != null) {
    Literal literal = model.createTypedLiteral(o, x);
    resourceGeometry.addLiteral(property, literal);
  } else {
    resourceGeometry.addProperty(property, o);
  }
}
 
Example 17
Source Project: TripleGeo   Source File: ShpConnector.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * 
 * Handle triples for string literals
 */
private void insertLiteralTriplet(String s, String p, String o, String x) 
{
  Resource resourceGeometry = model.createResource(s);
  Property property = model.createProperty(p);
  if (x != null) {
    Literal literal = model.createTypedLiteral(o, x);
    resourceGeometry.addLiteral(property, literal);
  } else {
    resourceGeometry.addProperty(property, o);
  }
}
 
Example 18
Source Project: TripleGeo   Source File: ShpConnector.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
*   
* Handle string literals for 'name' attribute
*/
 private void insertResourceNameLiteral(String s, String p, String o, String lang) 
 {
  	Resource resource = model.createResource(s);
    Property property = model.createProperty(p);
    if (lang != null) {
      Literal literal = model.createLiteral(o, lang);
      resource.addLiteral(property, literal);
    } else {
      resource.addProperty(property, o);
    }
  }
 
Example 19
Source Project: GeoTriples   Source File: ResourceMap.java    License: Apache License 2.0 4 votes vote down vote up
public Collection<Literal> getDefinitionLabels() {
	return definitionLabels;
}
 
Example 20
Source Project: GeoTriples   Source File: ResourceMap.java    License: Apache License 2.0 4 votes vote down vote up
public Collection<Literal> getDefinitionComments() {
	return definitionComments;
}
 
Example 21
Source Project: GeoTriples   Source File: ResourceMap.java    License: Apache License 2.0 4 votes vote down vote up
public void addDefinitionLabel(Literal definitionLabel) {
	definitionLabels.add(definitionLabel);
}
 
Example 22
Source Project: GeoTriples   Source File: ResourceMap.java    License: Apache License 2.0 4 votes vote down vote up
public void addDefinitionComment(Literal definitionComment) {
	definitionComments.add(definitionComment);
}
 
Example 23
Source Project: GeoTriples   Source File: R2RMLReader.java    License: Apache License 2.0 4 votes vote down vote up
public boolean isTypeOf(RDFNode node) {
	if (!node.isLiteral()) return false;
	Literal l = node.asLiteral();
	return XSD.xstring.getURI().equals(l.getDatatypeURI())
			|| (l.getDatatypeURI() == null && "".equals(l.getLanguage()));
}
 
Example 24
Source Project: semweb4j   Source File: DataTypeTesting.java    License: BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Test
public void testOldDataTypesUsedAsIntended() throws Exception {
	
	// laut der jena-dev Mailingliste, sollte man Datentypen so erzeugen:
	// siehe http://groups.yahoo.com/group/jena-dev/message/14052
	
	// String dtURI = tmpProp.getRange().getURI();
	// RDFDatatype dt = TypeMapper.getInstance().getTypeByName(dtURI);
	// Literal tmpLit = tmpModel.createTypedLiteral("123", dt );
	
	// leider f�hrt das dann dazu das "test"^^xsd:funky equal zu "test" ist,
	// da dann xsd:funky ein unknown data type ist und
	// somit "test"^^xsd:funky genau wie ein plain literal behandelt wird.
	
	// die erste DatenTyp URI
	// URI testA = URIUtils.createURI("test://somedata-A");
	String strTestA = new String("test://somedata-A");
	// die zweite DatenTyp URI
	// URI testB = URIUtils.createURI("test://somedata-B");
	String strTestB = new String("test://somedata-B");
	
	// der erste BaseDatatype wird von der ersten DatenTyp URI erzeugt
	RDFDatatype DTtestA1 = TypeMapper.getInstance().getTypeByName(strTestA);
	// der zweite BaseDatatype ebenso
	RDFDatatype DTtestA2 = TypeMapper.getInstance().getTypeByName(strTestA);
	// f�r den dritten BaseDatatype nehmen wir eine neue Datentyp URI
	RDFDatatype DTtestB = TypeMapper.getInstance().getTypeByName(strTestB);
	
	com.hp.hpl.jena.rdf.model.Model model = ModelFactory.createDefaultModel();
	
	Literal litA11 = model.createTypedLiteral("teststring", DTtestA1);
	Literal litA12 = model.createTypedLiteral("teststring", DTtestA1);
	Literal litA2 = model.createTypedLiteral("teststring", DTtestA2);
	@SuppressWarnings("unused")
	Literal litB = model.createTypedLiteral("teststring", DTtestB);
	
	// alle Literals haben den gleichen Wert !
	
	// dann wollen wir mal schauen was passiert:
	
	// reflexivit�t: A == A , passt
	assertTrue(litA11.equals(litA11));
	// gleicher Inhalt, in zwei versch. Objekten, passt auch
	assertTrue(litA11.equals(litA12));
	// zwei Objekte, mit untersch. BaseDatatypes, von der gleichen Datatype
	// URI:
	
	assertTrue(litA11.equals(litA2));
	// und zur sicherheit: 2 versch Datentyp URIs:
	
	// -> das sollte eigentlich nicht sein
	// TODO jena bug assertFalse(litA11.equals(litB));
	
}
 
Example 25
Source Project: semweb4j   Source File: DataTypeTesting.java    License: BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Test
public void testDataTypesWithUnknownType() throws Exception {
	
	// siehe dazu com.hp.hpl.jena.graph.test.TestTypedLiterals.java,
	// Funktion testUnknown()
	// das ganze funktioniert sowohl mit Jena2.2 als auch mit dem jena aus
	// dem cvs
	
	// das ganze Problem scheint wohl zu sein das Jena ziemlich abgefahrene
	// Sachen machen kann
	// mit daten typen und der valdierung und solchen advanced topics.
	// die Erwaeaehnte Test Datei zeigt das ziemlich eindrucksvoll.
	
	// Dieser gesamte Test testet direkt die Funktion von Jena, nicht von
	// rdf2go. (SG)
	
	// die erste DatenTyp URI
	String strTestA = new String("test://somedata-A");
	// die zweite DatenTyp URI
	String strTestB = new String("test://somedata-B");
	
	com.hp.hpl.jena.rdf.model.Model model = ModelFactory.createDefaultModel();
	
	// das hier scheint alles zu sein was notwendig ist damit Jena die data
	// typed literals
	// semantisch so behandelt wie wir es wollen
	// Behold !!
	JenaParameters.enableSilentAcceptanceOfUnknownDatatypes = true;
	
	Literal litA1 = model.createTypedLiteral("teststring", strTestA);
	Literal litA2 = model.createTypedLiteral("teststring", strTestA);
	Literal litB = model.createTypedLiteral("teststring", strTestB);
	
	// dann wollen wir mal schauen was passiert:
	
	// reflexivit�t: A == A , passt
	assertTrue(litA1.equals(litA1));
	// gleicher Inhalt, in zwei versch. Objekten, passt auch
	assertTrue(litA1.equals(litA2));
	// und zur sicherheit: 2 versch Datentyp URIs: nein
	assertFalse(litA1.equals(litB));
	
	// und nochmal der negativ Test:
	assertTrue(litB.equals(litB));
	assertFalse(litB.equals(litA1));
	assertFalse(litB.equals(litA2));
	assertEquals("Extract Datatype URI", litA1.getDatatypeURI(), strTestA);
	assertEquals("Extract value", "teststring", litA1.getLexicalForm());
	
	// im jena cvs geht auch folgendes, damit kann man das Object des Daten
	// Typs besser manipulieren
	// assertEquals("Extract value", l1.getValue(), new
	// BaseDatatype.TypedValue("foo", typeURI));
	
}
 
Example 26
Source Project: semanticMDR   Source File: Util.java    License: GNU General Public License v3.0 3 votes vote down vote up
/**
 * Creates {@link Literal} from Object
 * 
 * @param o
 *            is the Object which will be {@link Literal}
 * @return {@link Literal} object created from the Object, or null if the
 *         Object is null
 */
public Literal createTypedLiteral(Object o) {
	if (o == null) {
		return null;
	}
	return ontModel.createTypedLiteral(o);
}