Java Code Examples for com.hp.hpl.jena.datatypes.xsd.XSDDatatype

The following are top voted examples for showing how to use com.hp.hpl.jena.datatypes.xsd.XSDDatatype. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: r2rml-kit   File: TypedNodeMaker.java   Source Code and License 6 votes vote down vote up
public static NodeType typedLiteral(RDFDatatype datatype) {
	// TODO These subclasses can be abolished; just introduce an RDFDatatypeValidator instead
	if (datatype.equals(XSDDatatype.XSDdate)) {
		return XSD_DATE;
	}
	if (datatype.equals(XSDDatatype.XSDtime)) {
		return XSD_TIME;
	}
	if (datatype.equals(XSDDatatype.XSDdateTime)) {
		return XSD_DATETIME;
	}
	if (datatype.equals(XSDDatatype.XSDboolean)) {
		return XSD_BOOLEAN;
	}
	return new LiteralNodeType("", datatype);
}
 
Example 2
Project: r2rml-kit   File: PrettyPrinterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testNodePrettyPrinting() {
	assertEquals("\"foo\"", 
			PrettyPrinter.toString(Node.createLiteral("foo")));
	assertEquals("\"foo\"@en", 
			PrettyPrinter.toString(Node.createLiteral("foo", "en", null)));
	assertEquals("\"1\"^^xsd:int",
			PrettyPrinter.toString(Node.createLiteral("1", null, XSDDatatype.XSDint)));
	assertEquals("\"1\"^^xsd:int",
			PrettyPrinter.toString(Node.createLiteral("1", null, XSDDatatype.XSDint), PrefixMapping.Standard));
	assertEquals("_:foo", 
			PrettyPrinter.toString(Node.createAnon(new AnonId("foo"))));
	assertEquals("<http://example.org/>", 
			PrettyPrinter.toString(Node.createURI("http://example.org/")));
	assertEquals("<" + RDF.type.getURI() + ">", 
			PrettyPrinter.toString(RDF.type.asNode(), new PrefixMappingImpl()));
	assertEquals("rdf:type", 
			PrettyPrinter.toString(RDF.type.asNode(), PrefixMapping.Standard));
	assertEquals("?x", 
			PrettyPrinter.toString(Node.createVariable("x")));
	assertEquals("?ANY",
			PrettyPrinter.toString(Node.ANY));
}
 
Example 3
Project: c4a_data_repository   File: TypedNodeMaker.java   Source Code and License 6 votes vote down vote up
public static NodeType typedLiteral(RDFDatatype datatype) {
	// TODO These subclasses can be abolished; just introduce an RDFDatatypeValidator instead
	if (datatype.equals(XSDDatatype.XSDdate)) {
		return XSD_DATE;
	}
	if (datatype.equals(XSDDatatype.XSDtime)) {
		return XSD_TIME;
	}
	if (datatype.equals(XSDDatatype.XSDdateTime)) {
		return XSD_DATETIME;
	}
	if (datatype.equals(XSDDatatype.XSDboolean)) {
		return XSD_BOOLEAN;
	}
	return new LiteralNodeType("", datatype);
}
 
Example 4
Project: c4a_data_repository   File: MappingGenerator.java   Source Code and License 6 votes vote down vote up
public void writeColumn(Attribute column) {
	this.out.println(propertyBridgeIRITurtle(column) + " a d2rq:PropertyBridge;");
	this.out.println("\td2rq:belongsToClassMap " + classMapIRITurtle(column.relationName()) + ";");
	this.out.println("\td2rq:property " + vocabularyIRITurtle(column) + ";");
	if (generateDefinitionLabels) {
		this.out.println("\td2rq:propertyDefinitionLabel \"" + toLabel(column) + "\";");
	}
	this.out.println("\td2rq:column \"" + column.qualifiedName() + "\";");
	DataType colType = this.schema.columnType(column);
	String xsd = colType.rdfType();
	if (xsd != null && !"xsd:string".equals(xsd)) {
		// We use plain literals instead of xsd:strings, so skip
		// this if it's an xsd:string
		this.out.println("\td2rq:datatype " + xsd + ";");
	}
	if (colType.valueRegex() != null) {
		this.out.println("\td2rq:valueRegex \"" + colType.valueRegex() + "\";");
	}
	if (xsd == null) {
		createDatatypeProperty(column, null);
	} else {
		String datatypeURI = xsd.replaceAll("xsd:", XSDDatatype.XSD + "#");
		createDatatypeProperty(column, TypeMapper.getInstance().getSafeTypeByName(datatypeURI));
	}
	this.out.println("\t.");
}
 
Example 5
Project: c4a_data_repository   File: SPARQLTest.java   Source Code and License 6 votes vote down vote up
public void testSPARQLGetTopics() {
		sparql("SELECT ?x ?y WHERE { ?x skos:primarySubject ?z . ?z skos:prefLabel ?y }");
//		dump();

		expectVariable("x", this.model.createResource("http://test/papers/1"));
		expectVariable("y", this.model.createTypedLiteral("Semantic Web", XSDDatatype.XSDstring));
		assertSolution();

		expectVariable("x", this.model.createResource("http://test/papers/4"));
		expectVariable("y", this.model.createTypedLiteral("Semantic Web Infrastructure", XSDDatatype.XSDstring));
		assertSolution();

		expectVariable("x", this.model.createResource("http://test/papers/5"));
		expectVariable("y", this.model.createTypedLiteral("Artificial Intelligence", XSDDatatype.XSDstring));
		assertSolution();

		assertResultCount(3);
	}
 
Example 6
Project: c4a_data_repository   File: ExprTransformTest2.java   Source Code and License 6 votes vote down vote up
public void testDataType()
{
	List<Triple> pattern = new ArrayList<Triple>();
	pattern.add(Triple.create(Node.createVariable("s"), Node.createURI("http://example.org/value"), Node.createVariable("o")));
	NodeRelation[] rels = translate(pattern, "optimizer/filtertests.n3");
	
	NodeRelation intvalue = search("table2", "intvalue", rels);
	NodeRelation value = search("table2", "value", rels);
	
	pattern.clear();
	pattern.add(Triple.create(Node.createVariable("s"), RDFS.label.asNode(), Node.createVariable("o")));
	rels = translate(pattern, "optimizer/filtertests.n3");
	
	NodeRelation langliteral = search("table1", "label_en", rels);
	
	Expr filterint    = new E_Equals(new E_Datatype(new ExprVar("o")), NodeValueNode.makeNode(Node.createURI(XSDDatatype.XSDint.getURI())));
	Expr filterstring = new E_Equals(new E_Datatype(new ExprVar("o")), NodeValueNode.makeNode(Node.createURI(XSDDatatype.XSDstring.getURI())));
	
	assertEquals("DATATYPE(intliteral) = xsd:int should be TRUE",       Expression.TRUE, TransformExprToSQLApplyer.convert(filterint, intvalue));
	assertEquals("DATATYPE(simpleliteral) = xsd:string should be TRUE", Expression.TRUE, TransformExprToSQLApplyer.convert(filterstring, value));
	assertEquals("DATATYPE(langliteral) = xsd:string should be TRUE",   Expression.TRUE, TransformExprToSQLApplyer.convert(filterstring, langliteral));
}
 
Example 7
Project: c4a_data_repository   File: ExprTransformTest2.java   Source Code and License 6 votes vote down vote up
public void testDisjunction()
{
	List<Triple> pattern = new ArrayList<Triple>();
	pattern.add(Triple.create(Node.createVariable("s"), Node.createURI("http://example.org/value"), Node.createVariable("o")));
	NodeRelation[] rels = translate(pattern, "optimizer/filtertests.n3");
	
	NodeRelation intvalue = search("table2", "intvalue", rels);

	Expr disjunction = new E_LogicalOr(new E_Equals(new ExprVar("o"),  NodeValue.makeNode("1", XSDDatatype.XSDint)), new E_Equals(new ExprVar("o"), NodeValue.makeNode("2", XSDDatatype.XSDint)));
	
	Expression result = TransformExprToSQLApplyer.convert(disjunction, intvalue);
	TypedNodeMaker nm = (TypedNodeMaker) intvalue.nodeMaker(Var.alloc("o"));
	Expression e1 = nm.valueMaker().valueExpression("1");
	Expression e2 = nm.valueMaker().valueExpression("2");
	Expression expected = e1.or(e2);
	
	assertEquals("?o = \"1\"^^xsd:int || ?o = \"2\"^^xsd:int", expected, result);
}
 
Example 8
Project: c4a_data_repository   File: PrettyPrinterTest.java   Source Code and License 6 votes vote down vote up
public void testNodePrettyPrinting() {
	assertEquals("\"foo\"", 
			PrettyPrinter.toString(Node.createLiteral("foo")));
	assertEquals("\"foo\"@en", 
			PrettyPrinter.toString(Node.createLiteral("foo", "en", null)));
	assertEquals("\"1\"^^<" + XSDDatatype.XSDint.getURI() + ">",
			PrettyPrinter.toString(Node.createLiteral("1", null, XSDDatatype.XSDint)));
	assertEquals("\"1\"^^xsd:int",
			PrettyPrinter.toString(Node.createLiteral("1", null, XSDDatatype.XSDint), PrefixMapping.Standard));
	assertEquals("_:foo", 
			PrettyPrinter.toString(Node.createAnon(new AnonId("foo"))));
	assertEquals("<http://example.org/>", 
			PrettyPrinter.toString(Node.createURI("http://example.org/")));
	assertEquals("<" + RDF.type.getURI() + ">", 
			PrettyPrinter.toString(RDF.type.asNode(), new PrefixMappingImpl()));
	assertEquals("rdf:type", 
			PrettyPrinter.toString(RDF.type.asNode(), PrefixMapping.Standard));
	assertEquals("?x", 
			PrettyPrinter.toString(Node.createVariable("x")));
	assertEquals("?ANY",
			PrettyPrinter.toString(Node.ANY));
}
 
Example 9
Project: BimSPARQL   File: IsOutsidePF.java   Source Code and License 6 votes vote down vote up
@Override
protected QueryIterator verifyValue(Binding binding, Graph graph, Node product, Geometry geometry, Node object,
		ExecutionContext execCxt) {
	boolean b = false;
	try {
		if (product.getLocalName().equals("IfcWallStandardCase_5397")){
			System.out.println("");
		}
		HashSet<Geometry> allGeometries=getProcessableElements(graph);
		b = new ExternalQuadTreeImpl(geometry, allGeometries).getIsExternal();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	Node node = NodeFactory.createLiteral(Boolean.toString(b), null, XSDDatatype.XSDboolean);
	if (node.equals(object)) {
		return IterLib.result(binding, execCxt);
	} else {
		return IterLib.noResults(execCxt);
	}
}
 
Example 10
Project: statistics2cubes   File: Table2CubeConverter.java   Source Code and License 6 votes vote down vote up
private void createObservations(List<Property> headers, Resource ds) {
    HashMap<Integer, HashMap<String, Resource>> entities = createEntities();
    String obsPrefix = localNS.DATASET + "-" + id + "/" + localNS.OBS_NAME + "-";

    for (Row row : table.getRows()) {
        Resource obs = model.createResource(obsPrefix + UUID.randomUUID()).addProperty(RDF.type, QB.OBSERVATION);
        obs.addProperty(QB.DATASET_PROPERTY, ds);

        for (int i = 0; i < row.getCells().size(); i++) {
            Cell cell = row.getCells().get(i);

            if (i < getMeasureCount()) {
                // TODO use more data types
                XSDDatatype xsdDatatype = XSDDatatype.XSDdouble;
                Literal literal = model.createTypedLiteral(cell.getValue().getValue(), xsdDatatype);
                obs.addProperty(headers.get(i), literal);
            } else {
                Resource entity = entities.get(i).get(cell.getValue().getValue());
                obs.addProperty(headers.get(i), entity);
            }
        }
    }
}
 
Example 11
Project: statistics2cubes   File: Converter.java   Source Code and License 6 votes vote down vote up
private void createObservations(List<Property> headers, Resource ds) {
    HashMap<Integer, HashMap<String, Resource>> entities = createEntities();
    String obsPrefix = localNS.DATASET + "-" + id + "/" + localNS.OBS_NAME + "-";

    for (Row row : table.getRows()) {
        Resource obs = model.createResource(obsPrefix + UUID.randomUUID()).addProperty(RDF.type, QB.OBSERVATION);
        obs.addProperty(QB.DATASET_PROPERTY, ds);

        for (int i = 0; i < row.getCells().size(); i++) {
            Cell cell = row.getCells().get(i);

            if (i < getMeasureCount()) {
                // TODO use more data types
                XSDDatatype xsdDatatype = XSDDatatype.XSDdouble;
                Literal literal = model.createTypedLiteral(cell.getValue().getValue(), xsdDatatype);
                obs.addProperty(headers.get(i), literal);
            } else {
                Resource entity = entities.get(i).get(cell.getValue().getValue());
                obs.addProperty(headers.get(i), entity);
            }
        }
    }
}
 
Example 12
Project: OpenCollegeGraph   File: TypedNodeMaker.java   Source Code and License 6 votes vote down vote up
public static NodeType typedLiteral(RDFDatatype datatype) {
	// TODO These subclasses can be abolished; just introduce an RDFDatatypeValidator instead
	if (datatype.equals(XSDDatatype.XSDdate)) {
		return XSD_DATE;
	}
	if (datatype.equals(XSDDatatype.XSDtime)) {
		return XSD_TIME;
	}
	if (datatype.equals(XSDDatatype.XSDdateTime)) {
		return XSD_DATETIME;
	}
	if (datatype.equals(XSDDatatype.XSDboolean)) {
		return XSD_BOOLEAN;
	}
	return new LiteralNodeType("", datatype);
}
 
Example 13
Project: OpenCollegeGraph   File: MappingGenerator.java   Source Code and License 6 votes vote down vote up
public void writeColumn(Attribute column) {
	this.out.println(propertyBridgeIRITurtle(column) + " a d2rq:PropertyBridge;");
	this.out.println("\td2rq:belongsToClassMap " + classMapIRITurtle(column.relationName()) + ";");
	this.out.println("\td2rq:property " + vocabularyIRITurtle(column) + ";");
	if (generateDefinitionLabels) {
		this.out.println("\td2rq:propertyDefinitionLabel \"" + toLabel(column) + "\";");
	}
	this.out.println("\td2rq:column \"" + column.qualifiedName() + "\";");
	DataType colType = this.schema.columnType(column);
	String xsd = colType.rdfType();
	if (xsd != null && !"xsd:string".equals(xsd)) {
		// We use plain literals instead of xsd:strings, so skip
		// this if it's an xsd:string
		this.out.println("\td2rq:datatype " + xsd + ";");
	}
	if (colType.valueRegex() != null) {
		this.out.println("\td2rq:valueRegex \"" + colType.valueRegex() + "\";");
	}
	if (xsd == null) {
		createDatatypeProperty(column, null);
	} else {
		String datatypeURI = xsd.replaceAll("xsd:", XSDDatatype.XSD + "#");
		createDatatypeProperty(column, TypeMapper.getInstance().getSafeTypeByName(datatypeURI));
	}
	this.out.println("\t.");
}
 
Example 14
Project: OpenCollegeGraph   File: SPARQLTest.java   Source Code and License 6 votes vote down vote up
public void testSPARQLGetTopics() {
		sparql("SELECT ?x ?y WHERE { ?x skos:primarySubject ?z . ?z skos:prefLabel ?y }");
//		dump();

		expectVariable("x", this.model.createResource("http://test/papers/1"));
		expectVariable("y", this.model.createTypedLiteral("Semantic Web", XSDDatatype.XSDstring));
		assertSolution();

		expectVariable("x", this.model.createResource("http://test/papers/4"));
		expectVariable("y", this.model.createTypedLiteral("Semantic Web Infrastructure", XSDDatatype.XSDstring));
		assertSolution();

		expectVariable("x", this.model.createResource("http://test/papers/5"));
		expectVariable("y", this.model.createTypedLiteral("Artificial Intelligence", XSDDatatype.XSDstring));
		assertSolution();

		assertResultCount(3);
	}
 
Example 15
Project: OpenCollegeGraph   File: ExprTransformTest2.java   Source Code and License 6 votes vote down vote up
public void testDataType()
{
	List<Triple> pattern = new ArrayList<Triple>();
	pattern.add(Triple.create(Node.createVariable("s"), Node.createURI("http://example.org/value"), Node.createVariable("o")));
	NodeRelation[] rels = translate(pattern, "optimizer/filtertests.n3");
	
	NodeRelation intvalue = search("table2", "intvalue", rels);
	NodeRelation value = search("table2", "value", rels);
	
	pattern.clear();
	pattern.add(Triple.create(Node.createVariable("s"), RDFS.label.asNode(), Node.createVariable("o")));
	rels = translate(pattern, "optimizer/filtertests.n3");
	
	NodeRelation langliteral = search("table1", "label_en", rels);
	
	Expr filterint    = new E_Equals(new E_Datatype(new ExprVar("o")), NodeValueNode.makeNode(Node.createURI(XSDDatatype.XSDint.getURI())));
	Expr filterstring = new E_Equals(new E_Datatype(new ExprVar("o")), NodeValueNode.makeNode(Node.createURI(XSDDatatype.XSDstring.getURI())));
	
	assertEquals("DATATYPE(intliteral) = xsd:int should be TRUE",       Expression.TRUE, TransformExprToSQLApplyer.convert(filterint, intvalue));
	assertEquals("DATATYPE(simpleliteral) = xsd:string should be TRUE", Expression.TRUE, TransformExprToSQLApplyer.convert(filterstring, value));
	assertEquals("DATATYPE(langliteral) = xsd:string should be TRUE",   Expression.TRUE, TransformExprToSQLApplyer.convert(filterstring, langliteral));
}
 
Example 16
Project: OpenCollegeGraph   File: ExprTransformTest2.java   Source Code and License 6 votes vote down vote up
public void testDisjunction()
{
	List<Triple> pattern = new ArrayList<Triple>();
	pattern.add(Triple.create(Node.createVariable("s"), Node.createURI("http://example.org/value"), Node.createVariable("o")));
	NodeRelation[] rels = translate(pattern, "optimizer/filtertests.n3");
	
	NodeRelation intvalue = search("table2", "intvalue", rels);

	Expr disjunction = new E_LogicalOr(new E_Equals(new ExprVar("o"),  NodeValue.makeNode("1", XSDDatatype.XSDint)), new E_Equals(new ExprVar("o"), NodeValue.makeNode("2", XSDDatatype.XSDint)));
	
	Expression result = TransformExprToSQLApplyer.convert(disjunction, intvalue);
	TypedNodeMaker nm = (TypedNodeMaker) intvalue.nodeMaker(Var.alloc("o"));
	Expression e1 = nm.valueMaker().valueExpression("1");
	Expression e2 = nm.valueMaker().valueExpression("2");
	Expression expected = e1.or(e2);
	
	assertEquals("?o = \"1\"^^xsd:int || ?o = \"2\"^^xsd:int", expected, result);
}
 
Example 17
Project: OpenCollegeGraph   File: PrettyPrinterTest.java   Source Code and License 6 votes vote down vote up
public void testNodePrettyPrinting() {
	assertEquals("\"foo\"", 
			PrettyPrinter.toString(Node.createLiteral("foo")));
	assertEquals("\"foo\"@en", 
			PrettyPrinter.toString(Node.createLiteral("foo", "en", null)));
	assertEquals("\"1\"^^<" + XSDDatatype.XSDint.getURI() + ">",
			PrettyPrinter.toString(Node.createLiteral("1", null, XSDDatatype.XSDint)));
	assertEquals("\"1\"^^xsd:int",
			PrettyPrinter.toString(Node.createLiteral("1", null, XSDDatatype.XSDint), PrefixMapping.Standard));
	assertEquals("_:foo", 
			PrettyPrinter.toString(Node.createAnon(new AnonId("foo"))));
	assertEquals("<http://example.org/>", 
			PrettyPrinter.toString(Node.createURI("http://example.org/")));
	assertEquals("<" + RDF.type.getURI() + ">", 
			PrettyPrinter.toString(RDF.type.asNode(), new PrefixMappingImpl()));
	assertEquals("rdf:type", 
			PrettyPrinter.toString(RDF.type.asNode(), PrefixMapping.Standard));
	assertEquals("?x", 
			PrettyPrinter.toString(Node.createVariable("x")));
	assertEquals("?ANY",
			PrettyPrinter.toString(Node.ANY));
}
 
Example 18
Project: VirtualSPARQLer   File: TypedNodeMaker.java   Source Code and License 6 votes vote down vote up
public static NodeType typedLiteral(RDFDatatype datatype) {
	// TODO These subclasses can be abolished; just introduce an RDFDatatypeValidator instead
	if (datatype.equals(XSDDatatype.XSDdate)) {
		return XSD_DATE;
	}
	if (datatype.equals(XSDDatatype.XSDtime)) {
		return XSD_TIME;
	}
	if (datatype.equals(XSDDatatype.XSDdateTime)) {
		return XSD_DATETIME;
	}
	if (datatype.equals(XSDDatatype.XSDboolean)) {
		return XSD_BOOLEAN;
	}
	return new LiteralNodeType("", datatype);
}
 
Example 19
Project: VirtualSPARQLer   File: MappingGenerator.java   Source Code and License 6 votes vote down vote up
public void writeColumn(Attribute column) {
	this.out.println(propertyBridgeIRITurtle(column) + " a d2rq:PropertyBridge;");
	this.out.println("\td2rq:belongsToClassMap " + classMapIRITurtle(column.relationName()) + ";");
	this.out.println("\td2rq:property " + vocabularyIRITurtle(column) + ";");
	if (generateDefinitionLabels) {
		this.out.println("\td2rq:propertyDefinitionLabel \"" + toLabel(column) + "\";");
	}
	this.out.println("\td2rq:column \"" + column.qualifiedName() + "\";");
	DataType colType = this.schema.columnType(column);
	String xsd = colType.rdfType();
	if (xsd != null && !"xsd:string".equals(xsd)) {
		// We use plain literals instead of xsd:strings, so skip
		// this if it's an xsd:string
		this.out.println("\td2rq:datatype " + xsd + ";");
	}
	if (colType.valueRegex() != null) {
		this.out.println("\td2rq:valueRegex \"" + colType.valueRegex() + "\";");
	}
	if (xsd == null) {
		createDatatypeProperty(column, null);
	} else {
		String datatypeURI = xsd.replaceAll("xsd:", XSDDatatype.XSD + "#");
		createDatatypeProperty(column, TypeMapper.getInstance().getSafeTypeByName(datatypeURI));
	}
	this.out.println("\t.");
}
 
Example 20
Project: VirtualSPARQLer   File: SPARQLTest.java   Source Code and License 6 votes vote down vote up
public void testSPARQLGetTopics() {
		sparql("SELECT ?x ?y WHERE { ?x skos:primarySubject ?z . ?z skos:prefLabel ?y }");
//		dump();

		expectVariable("x", this.model.createResource("http://test/papers/1"));
		expectVariable("y", this.model.createTypedLiteral("Semantic Web", XSDDatatype.XSDstring));
		assertSolution();

		expectVariable("x", this.model.createResource("http://test/papers/4"));
		expectVariable("y", this.model.createTypedLiteral("Semantic Web Infrastructure", XSDDatatype.XSDstring));
		assertSolution();

		expectVariable("x", this.model.createResource("http://test/papers/5"));
		expectVariable("y", this.model.createTypedLiteral("Artificial Intelligence", XSDDatatype.XSDstring));
		assertSolution();

		assertResultCount(3);
	}
 
Example 21
Project: VirtualSPARQLer   File: ExprTransformTest2.java   Source Code and License 6 votes vote down vote up
public void testDataType()
{
	List<Triple> pattern = new ArrayList<Triple>();
	pattern.add(Triple.create(Node.createVariable("s"), Node.createURI("http://example.org/value"), Node.createVariable("o")));
	NodeRelation[] rels = translate(pattern, "optimizer/filtertests.n3");
	
	NodeRelation intvalue = search("table2", "intvalue", rels);
	NodeRelation value = search("table2", "value", rels);
	
	pattern.clear();
	pattern.add(Triple.create(Node.createVariable("s"), RDFS.label.asNode(), Node.createVariable("o")));
	rels = translate(pattern, "optimizer/filtertests.n3");
	
	NodeRelation langliteral = search("table1", "label_en", rels);
	
	Expr filterint    = new E_Equals(new E_Datatype(new ExprVar("o")), NodeValueNode.makeNode(Node.createURI(XSDDatatype.XSDint.getURI())));
	Expr filterstring = new E_Equals(new E_Datatype(new ExprVar("o")), NodeValueNode.makeNode(Node.createURI(XSDDatatype.XSDstring.getURI())));
	
	assertEquals("DATATYPE(intliteral) = xsd:int should be TRUE",       Expression.TRUE, TransformExprToSQLApplyer.convert(filterint, intvalue));
	assertEquals("DATATYPE(simpleliteral) = xsd:string should be TRUE", Expression.TRUE, TransformExprToSQLApplyer.convert(filterstring, value));
	assertEquals("DATATYPE(langliteral) = xsd:string should be TRUE",   Expression.TRUE, TransformExprToSQLApplyer.convert(filterstring, langliteral));
}
 
Example 22
Project: VirtualSPARQLer   File: ExprTransformTest2.java   Source Code and License 6 votes vote down vote up
public void testDisjunction()
{
	List<Triple> pattern = new ArrayList<Triple>();
	pattern.add(Triple.create(Node.createVariable("s"), Node.createURI("http://example.org/value"), Node.createVariable("o")));
	NodeRelation[] rels = translate(pattern, "optimizer/filtertests.n3");
	
	NodeRelation intvalue = search("table2", "intvalue", rels);

	Expr disjunction = new E_LogicalOr(new E_Equals(new ExprVar("o"),  NodeValue.makeNode("1", XSDDatatype.XSDint)), new E_Equals(new ExprVar("o"), NodeValue.makeNode("2", XSDDatatype.XSDint)));
	
	Expression result = TransformExprToSQLApplyer.convert(disjunction, intvalue);
	TypedNodeMaker nm = (TypedNodeMaker) intvalue.nodeMaker(Var.alloc("o"));
	Expression e1 = nm.valueMaker().valueExpression("1");
	Expression e2 = nm.valueMaker().valueExpression("2");
	Expression expected = e1.or(e2);
	
	assertEquals("?o = \"1\"^^xsd:int || ?o = \"2\"^^xsd:int", expected, result);
}
 
Example 23
Project: VirtualSPARQLer   File: PrettyPrinterTest.java   Source Code and License 6 votes vote down vote up
public void testNodePrettyPrinting() {
	assertEquals("\"foo\"", 
			PrettyPrinter.toString(Node.createLiteral("foo")));
	assertEquals("\"foo\"@en", 
			PrettyPrinter.toString(Node.createLiteral("foo", "en", null)));
	assertEquals("\"1\"^^<" + XSDDatatype.XSDint.getURI() + ">",
			PrettyPrinter.toString(Node.createLiteral("1", null, XSDDatatype.XSDint)));
	assertEquals("\"1\"^^xsd:int",
			PrettyPrinter.toString(Node.createLiteral("1", null, XSDDatatype.XSDint), PrefixMapping.Standard));
	assertEquals("_:foo", 
			PrettyPrinter.toString(Node.createAnon(new AnonId("foo"))));
	assertEquals("<http://example.org/>", 
			PrettyPrinter.toString(Node.createURI("http://example.org/")));
	assertEquals("<" + RDF.type.getURI() + ">", 
			PrettyPrinter.toString(RDF.type.asNode(), new PrefixMappingImpl()));
	assertEquals("rdf:type", 
			PrettyPrinter.toString(RDF.type.asNode(), PrefixMapping.Standard));
	assertEquals("?x", 
			PrettyPrinter.toString(Node.createVariable("x")));
	assertEquals("?ANY",
			PrettyPrinter.toString(Node.ANY));
}
 
Example 24
Project: EarmarkDataStructure   File: JenaWriter.java   Source Code and License 6 votes vote down vote up
private Resource readXPathPointerRange(XPathPointerRange item) {
	Resource result = addRangeProperties(item, XSDDatatype.XSDnonNegativeInteger);
	
	Statement statement = null;
	
	String hasXPathContext = item.hasXPathContext();
	try {
		result.addProperty(phasxpathcontext_r, hasXPathContext.toString(), XSDDatatype.XSDstring);
	} catch (NullPointerException e) {
		getLogger().warning("The XPath pointer range " + item.hasId() + " has not any XPath context specified" 
				+ " [in 'readXPathPointerRange' method]\nException: " + e.getMessage());
		statement = model.createStatement(result, RDF.type, xpathpointerrange_r);
		
	}
	
	if (statement == null) {
		model.add(result, RDF.type, xpathpointerrange_r);
	} else {
		model.add(statement);
	}
	
	return result;
}
 
Example 25
Project: EarmarkDataStructure   File: JenaReader.java   Source Code and License 6 votes vote down vote up
private Docuverse readDocuverse(Resource resource) {
	Docuverse result = null;
	
	Statement hasContent = resource.getProperty(phascontent_r);
	
	try {
		if (hasContent.getObject().asNode().getLiteralDatatype().equals(XSDDatatype.XSDanyURI)) {
			result = readURIDocuverse(resource);
		} else {
			result = readStringDocuverse(resource);
		}
	} catch (Exception e) {
		result = readStringDocuverse(resource);
	}
	
	return result;
}
 
Example 26
Project: parkjam   File: Rule.java   Source Code and License 6 votes vote down vote up
/**
 * Turn a possible numeric token into typed literal else a plain literal
 * @return the constructed literal node
 */
Node parseNumber(String lit) {
    if ( Character.isDigit(lit.charAt(0)) || 
        (lit.charAt(0) == '-' && lit.length() > 1 && Character.isDigit(lit.charAt(1))) ) {
        if (lit.indexOf(".") != -1) {
            // Float?
            if (XSDDatatype.XSDfloat.isValid(lit)) {
                return Node.createLiteral(lit, "", XSDDatatype.XSDfloat);
            }
        } else {
            // Int?
            if (XSDDatatype.XSDint.isValid(lit)) {
                return Node.createLiteral(lit, "", XSDDatatype.XSDint);
            }
        }
    }
    // Default is a plain literal
    return Node.createLiteral(lit, "", false);
}
 
Example 27
Project: oro-server   File: Namespaces.java   Source Code and License 6 votes vote down vote up
/**
 * Convert a resource to its string representation and try to replace the namespace by its prefix (or remove it if it's the default one).<br/>
 * It uses {@link #contract(String)} to replace or remove the namespace.<br/>
 * If the prefix for the namespace is unknown, complete URI is returned.
 * 
 * @param res The RDFNode which is to output as a string.
 * @return The literal representation of the resource, with short namespace (or no namespace if it is the default one).
 */
public static String toLightString(final RDFNode res)
{
	if (res.isAnon()) return "anonymousNode_" + res.toString();
	
	if (res.isResource() && ((Resource)res).getURI() != null) 
		return contract(((Resource)res).getURI());
	
	if (res.isLiteral())
	{
		Literal lit = (Literal)res;
		if (lit.getDatatype() == XSDDatatype.XSDdouble ||
			lit.getDatatype() == XSDDatatype.XSDint ||
			lit.getDatatype() == XSDDatatype.XSDboolean)
			return lit.getLexicalForm();
		
		if (lit.getDatatype() == null) //plain literal
			return lit.getLexicalForm();
		
		return "'" + lit.getLexicalForm() + "'^^" + contract((lit).getDatatypeURI());
	}
	
	return res.toString();
}
 
Example 28
Project: enviroCar-server   File: MeasurementSSNLinker.java   Source Code and License 6 votes vote down vote up
protected Resource createAmount(Model m, Resource measurement,
                                MeasurementValue v, Resource unit) {
    Resource amount = m.createResource(
            fragment(measurement, v.getPhenomenon().getName() +
                                  VALUE_FRAGMENT_POSTFIX));
    amount.addProperty(RDF.type, DUL.Amount);
    amount.addProperty(DUL.isClassifiedBy, unit);

    if (v.getValue() instanceof Number) {
        amount.addLiteral(DUL.hasDataValue,
                          ((Number) v.getValue()).doubleValue());
    } else if (v.getValue() instanceof Boolean) {
        amount.addLiteral(DUL.hasDataValue,
                          ((Boolean) v.getValue()).booleanValue());
    } else if (v.getValue() instanceof String) {
        amount.addProperty(DUL.hasDataValue,
                           (String) v.getValue(),
                           XSDDatatype.XSDstring);
    } else {
        amount.addProperty(DUL.hasDataValue,
                           v.getValue().toString(),
                           XSDDatatype.XSDstring);
    }
    return amount;
}
 
Example 29
Project: bacon   File: MergeDao.java   Source Code and License 6 votes vote down vote up
private Cube addBasicInfo(String graph, String userId) {
    ParameterizedSparqlString prepareQuery = new ParameterizedSparqlString(QUERY_CUBE_INFO);
    prepareQuery.setIri("g", graph);
    prepareQuery.setLiteral("auth", userId, XSDDatatype.XSDstring);

    QueryEngineHTTP qeHTTP = (QueryEngineHTTP) QueryExecutionFactory.sparqlService(TRIPLE_STORE, prepareQuery.toString());
    ResultSet rs = qeHTTP.execSelect();
    Cube cube = new Cube();

    if (rs.hasNext()) {
        QuerySolution result = rs.next();
        cube.setGraph(graph);
        cube.setAuth(userId);
        cube.setLabel(result.get("label").toString());
        cube.setId(result.get("id").toString());
        cube.setDescription(result.get("description").toString());
    }

    qeHTTP.close();

    return cube;
}
 
Example 30
Project: bacon   File: MergeDao.java   Source Code and License 6 votes vote down vote up
public DatasetDescription getDatasetFromUser(String graph, String userId) {
    ParameterizedSparqlString prepareQuery = new ParameterizedSparqlString(QUERY_DATASET_DESCRIPTION);
    prepareQuery.setIri("g", graph);
    prepareQuery.setLiteral("auth", userId, XSDDatatype.XSDstring);

    QueryEngineHTTP qeHTTP = (QueryEngineHTTP) QueryExecutionFactory.sparqlService(TRIPLE_STORE, prepareQuery.toString());
    ResultSet rs = qeHTTP.execSelect();

    DatasetDescription dd = new DatasetDescription();

    if (rs.hasNext()) {
        QuerySolution result = rs.next();

        dd.setNamedGraph(graph);
        dd.setDatasetId(result.get("id").toString());
        dd.setLabel(result.get("label").toString());
        dd.setDescription(result.get("description").toString());
    }

    qeHTTP.close();

    return dd;
}
 
Example 31
Project: bacon   File: MergeDao.java   Source Code and License 6 votes vote down vote up
public List<DatasetDescription> getDatasetsFromUser(String userId) {
    ParameterizedSparqlString prepareQuery = new ParameterizedSparqlString(QUERY_DATASET_DESCRIPTIONS);
    prepareQuery.setLiteral("auth", userId, XSDDatatype.XSDstring);

    QueryEngineHTTP qeHTTP = (QueryEngineHTTP) QueryExecutionFactory.sparqlService(TRIPLE_STORE, prepareQuery.toString());
    ResultSet rs = qeHTTP.execSelect();
    List<DatasetDescription> descriptions = new LinkedList<DatasetDescription>();

    while (rs.hasNext()) {
        QuerySolution result = rs.next();
        DatasetDescription dd = new DatasetDescription();
        dd.setNamedGraph(result.get("g").toString());
        dd.setDatasetId(result.get("id").toString());
        dd.setLabel(result.get("label").toString());
        dd.setDescription(result.get("description").toString());

        descriptions.add(dd);
    }

    qeHTTP.close();

    return descriptions;
}
 
Example 32
Project: harvesters   File: SellersImpl.java   Source Code and License 5 votes vote down vote up
public static void espaSellers() {

        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
        SellersService sellers = (SellersService) ctx.getBean("sellersServiceImpl");

        List<Sellers> seller = sellers.getSellers();

        //--------------RDF Model--------------//
        Model model = ModelFactory.createDefaultModel();
        Reasoner reasoner = ReasonerRegistry.getOWLReasoner();
        InfModel infModel = ModelFactory.createInfModel(reasoner, model);

        model.setNsPrefix("elod", OntologySpecification.elodPrefix);
        model.setNsPrefix("gr", OntologySpecification.goodRelationsPrefix);
        model.setNsPrefix("vcard", OntologySpecification.vcardPrefix);

        for (Sellers seller1 : seller) {
            Resource instanceSeller = infModel.createResource(OntologySpecification.instancePrefix + "Organization/" + seller1.getId());
            infModel.add(instanceSeller, RDF.type, OntologySpecification.organizationResource);
            instanceSeller.addProperty(OntologySpecification.name, seller1.getEponimia(), XSDDatatype.XSDstring);
        }

        try {
            FileOutputStream fout = new FileOutputStream(
                    "/Users/giovaf/Documents/yds_pilot1/espa_tests/22-02-2016_ouput/sellersEspa.rdf");
            model.write(fout);
        } catch (IOException e) {
            System.out.println("Exception caught" + e.getMessage());
        }
    }
 
Example 33
Project: ld-sniffer   File: Evaluation.java   Source Code and License 5 votes vote down vote up
public void addEvaluationActivity(Model model, Date startTime, Date endTime) {

        evaluation.addProperty(RDF.type, EVAL.Evaluation);
        evaluation.addProperty(RDF.type, PROV.Activity);
        evaluation.addLiteral(EVAL.performedOn, ResourceFactory.createTypedLiteral( DATE_FORMAT.format(startTime), XSDDatatype.XSDdateTime));
        evaluation.addLiteral(PROV.startedAtTime, ResourceFactory.createTypedLiteral( DATE_FORMAT.format(startTime), XSDDatatype.XSDdateTime));
        evaluation.addLiteral(PROV.endedAtTime, ResourceFactory.createTypedLiteral( DATE_FORMAT.format(endTime), XSDDatatype.XSDdateTime));
        evaluation.addProperty(EVAL.evaluatedSubject, subject);
        evaluation.addProperty(LDQ.utilizes, LDQM.AT_SPARQL_Query);
        evaluation.addProperty(LDQ.utilizes, LDQM.AT_Url_Dereferencing);
    }
 
Example 34
Project: ld-sniffer   File: Evaluation.java   Source Code and License 5 votes vote down vote up
public void addDereferenceabilityMeasure(Model model, HttpResponse response) {
    Resource subject = model.createResource(response.getUri());
    try {
        subject.addProperty(URI4URI.host, new URI(response.getUri()).getHost());
    } catch (URISyntaxException e) {
        //We quietly ignore if we can't parse the URI
    }
    Resource measure = addMeasure(model, LDQM.IRIdereferenceability, subject);
    if (response.getStatusCode() >= 200 && response.getStatusCode() < 300 ) {
        measure.addLiteral(DQV.value, model.createTypedLiteral(true, XSDDatatype.XSDboolean));
        measure.addLiteral(EVAL.hasLiteralValue, model.createTypedLiteral(true, XSDDatatype.XSDboolean));
    } else {
        measure.addLiteral(DQV.value, model.createTypedLiteral(false, XSDDatatype.XSDboolean));
        measure.addLiteral(EVAL.hasLiteralValue, model.createTypedLiteral(false, XSDDatatype.XSDboolean));
    }
    Resource request = model.createResource(HTTP.Request);
    measure.addProperty(DCTerms.references, request);
    request.addLiteral(HTTP.methodName, response.getMethod());
    request.addLiteral(HTTP.httpVersion, "1.1");
    request.addLiteral(DCTerms.date, model.createTypedLiteral(DATE_FORMAT.format(response.getDate()),XSDDatatype.XSDdateTime));

    Resource res = model.createResource(HTTP.Response);
    request.addProperty(HTTP.resp, res);
    if (response.getStatusCode() > 0) {
        res.addLiteral(HTTP.statusCodeValue, model.createTypedLiteral(response.getStatusCode(),XSDDatatype.XSDint));
    }
    if (response.getReason() != null){
        res.addLiteral(HTTP.reasonPhrase, response.getReason());
    }
}
 
Example 35
Project: r2rml-kit   File: JenaGraphExample.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
	// Load mapping file
	Model mapModel = FileManager.get().loadModel("doc/example/mapping-iswc.ttl");
	
	// Read mapping file
	D2RQReader reader = new D2RQReader(mapModel, "http://localhost:2020/");
	Mapping mapping = reader.getMapping();
	
	// Compile mapping for D2RQ engine
	CompiledMapping compiled = mapping.compile();

	// Set up the GraphD2RQ
	GraphD2RQ g = new GraphD2RQ(compiled);

	// Create a find(spo) pattern 
	Node subject = Node.ANY;
	Node predicate = DC.date.asNode();
	Node object = Node.createLiteral("2003", null, XSDDatatype.XSDgYear);
	Triple pattern = new Triple(subject, predicate, object);

	// Query the graph
	Iterator<Triple> it = g.find(pattern);
	
	// Output query results
	while (it.hasNext()) {
		Triple t = it.next();
	    System.out.println("Published in 2003: " + t.getSubject());
	}
	g.close();
}
 
Example 36
Project: r2rml-kit   File: FindTest.java   Source Code and License 5 votes vote down vote up
@Test
	public void testDatatypeFindByYear() {
		find(null, DC.date, createTypedLiteral("2003", XSDDatatype.XSDgYear));
//		dump();
		assertStatement(resource("papers/4"), DC.date, createTypedLiteral("2003", XSDDatatype.XSDgYear));
		assertStatementCount(1);
	}
 
Example 37
Project: r2rml-kit   File: FindTest.java   Source Code and License 5 votes vote down vote up
@Test
	public void testDatatypeFindByString() {
		find(null, SKOS.prefLabel, createTypedLiteral("E-Business", XSDDatatype.XSDstring));
//		dump();
		assertStatement(resource("topics/13"), SKOS.prefLabel, createTypedLiteral("E-Business", XSDDatatype.XSDstring));
		assertStatementCount(1);
	}
 
Example 38
Project: r2rml-kit   File: FindTest.java   Source Code and License 5 votes vote down vote up
@Test
	public void testDatatypeFindYear() {
		find(resource("papers/2"), DC.date, null);
//		dump();
		assertStatement(resource("papers/2"), DC.date, createTypedLiteral("2002", XSDDatatype.XSDgYear));
		assertStatementCount(1);
	}
 
Example 39
Project: r2rml-kit   File: FindTest.java   Source Code and License 5 votes vote down vote up
@Test
	public void testDatatypeYearContains() {
		find(resource("papers/2"), DC.date, createTypedLiteral("2002", XSDDatatype.XSDgYear));
//		dump();
		assertStatement(resource("papers/2"), DC.date, createTypedLiteral("2002", XSDDatatype.XSDgYear));
		assertStatementCount(1);
	}
 
Example 40
Project: r2rml-kit   File: FindTest.java   Source Code and License 5 votes vote down vote up
@Test
	public void testFindPredicate() {
		find(resource("papers/2"), null, createTypedLiteral("2002", XSDDatatype.XSDgYear));
//		dump();
		assertStatement(resource("papers/2"), DC.date, createTypedLiteral("2002", XSDDatatype.XSDgYear));
		assertStatementCount(1);
    }