org.eclipse.rdf4j.model.Literal Java Examples

The following examples show how to use org.eclipse.rdf4j.model.Literal. 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: QueryModelBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public ValueConstant visit(ASTLiteral litNode, Object data) throws VisitorException {
	IRI datatype = null;

	// Get datatype URI from child URI node, if present
	ASTValueExpr dtNode = litNode.getDatatypeNode();
	if (dtNode instanceof ASTURI) {
		datatype = valueFactory.createIRI(((ASTURI) dtNode).getValue());
	} else if (dtNode != null) {
		throw new IllegalArgumentException("Unexpected datatype type: " + dtNode.getClass());
	}

	Literal literal;
	if (datatype != null) {
		literal = valueFactory.createLiteral(litNode.getLabel(), datatype);
	} else if (litNode.hasLang()) {
		literal = valueFactory.createLiteral(litNode.getLabel(), litNode.getLang());
	} else {
		literal = valueFactory.createLiteral(litNode.getLabel());
	}

	return new ValueConstant(literal);
}
 
Example #2
Source File: RdfToRyaConversions.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Converts a {@link Value} into a {@link RyaType} representation of the
 * {@code value}.
 * @param value the {@link Value} to convert.
 * @return the {@link RyaType} representation of the {@code value}.
 */
public static RyaType convertValue(final Value value) {
    if (value == null) {
        return null;
    }
    //assuming either IRI or Literal here
    if (value instanceof Resource) {
        return convertResource((Resource) value);
    }
    if (value instanceof Literal) {
        return convertLiteral((Literal) value);
    }
    if (value instanceof RangeValue) {
        final RangeValue<?> rv = (RangeValue<?>) value;
        if (rv.getStart() instanceof IRI) {
            return new RyaIRIRange(convertIRI((IRI) rv.getStart()), convertIRI((IRI) rv.getEnd()));
        } else {
            //literal
            return new RyaTypeRange(convertLiteral((Literal) rv.getStart()), convertLiteral((Literal) rv.getEnd()));
        }
    }
    return null;
}
 
Example #3
Source File: SpinParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private int getMaxIterationCount(Resource ruleProp, TripleSource store) throws RDF4JException {
	Value v = TripleSources.singleValue(ruleProp, SPIN.RULE_PROPERTY_MAX_ITERATION_COUNT_PROPERTY, store);
	if (v == null) {
		return -1;
	} else if (v instanceof Literal) {
		try {
			return ((Literal) v).intValue();
		} catch (NumberFormatException e) {
			throw new MalformedSpinException("Value for " + SPIN.RULE_PROPERTY_MAX_ITERATION_COUNT_PROPERTY
					+ " must be of datatype " + XMLSchema.INTEGER + ": " + ruleProp);
		}
	} else {
		throw new MalformedSpinException(
				"Non-literal value for " + SPIN.RULE_PROPERTY_MAX_ITERATION_COUNT_PROPERTY + ": " + ruleProp);
	}
}
 
Example #4
Source File: ReplaceTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testEvaluate3() {

	Literal arg = f.createLiteral("foobar");
	Literal pattern = f.createLiteral("BA");
	Literal replacement = f.createLiteral("Z");
	Literal flags = f.createLiteral("i");

	try {
		Literal result = replaceFunc.evaluate(f, arg, pattern, replacement, flags);

		assertEquals("fooZr", result.getLabel());
	} catch (ValueExprEvaluationException e) {
		fail(e.getMessage());
	}
}
 
Example #5
Source File: ModelsTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testSetProperty() {
	Literal lit1 = VF.createLiteral(1.0);
	model1.add(foo, bar, lit1);
	model1.add(foo, bar, foo);

	Literal lit2 = VF.createLiteral(2.0);

	Model m = Models.setProperty(model1, foo, bar, lit2);

	assertNotNull(m);
	assertEquals(model1, m);
	assertFalse(model1.contains(foo, bar, lit1));
	assertFalse(model1.contains(foo, bar, foo));
	assertTrue(model1.contains(foo, bar, lit2));

}
 
Example #6
Source File: HBaseSail.java    From Halyard with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize() throws SailException { //initialize the SAIL
    try {
    	    //get or create and get the HBase table
        table = HalyardTableUtils.getTable(config, tableName, create, splitBits);

        //Iterate over statements relating to namespaces and add them to the namespace map.
        try (CloseableIteration<? extends Statement, SailException> nsIter = getStatements(null, HALYARD.NAMESPACE_PREFIX_PROPERTY, null, true)) {
            while (nsIter.hasNext()) {
                Statement st = nsIter.next();
                if (st.getObject() instanceof Literal) {
                    String prefix = st.getObject().stringValue();
                    String name = st.getSubject().stringValue();
                    namespaces.put(prefix, new SimpleNamespace(prefix, name));
                }
            }
        }
    } catch (IOException ex) {
        throw new SailException(ex);
    }
}
 
Example #7
Source File: CountFunction.java    From rya with Apache License 2.0 6 votes vote down vote up
@Override
public void update(final AggregationElement aggregation, final AggregationState state, final VisibilityBindingSet childBindingSet) {
    checkArgument(aggregation.getAggregationType() == AggregationType.COUNT, "The CountFunction only accepts COUNT AggregationElements.");
    requireNonNull(state);
    requireNonNull(childBindingSet);

    // Only add one to the count if the child contains the binding that we are counting.
    final String aggregatedName = aggregation.getAggregatedBindingName();
    if(childBindingSet.hasBinding(aggregatedName)) {
        final MapBindingSet result = state.getBindingSet();
        final String resultName = aggregation.getResultBindingName();
        final boolean newBinding = !result.hasBinding(resultName);

        if(newBinding) {
            // Initialize the binding.
            result.addBinding(resultName, VF.createLiteral(BigInteger.ONE));
        } else {
            // Update the existing binding.
            final Literal count = (Literal) result.getValue(resultName);
            final BigInteger updatedCount = count.integerValue().add( BigInteger.ONE );
            result.addBinding(resultName, VF.createLiteral(updatedCount));
        }
    }
}
 
Example #8
Source File: HalyardStrategyExtendedTest.java    From Halyard with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubqueries() throws Exception {
    ValueFactory vf = con.getValueFactory();
    con.add(vf.createIRI("http://whatever/a"), vf.createIRI("http://whatever/val"), vf.createLiteral(1));
    con.add(vf.createIRI("http://whatever/b"), vf.createIRI("http://whatever/val"), vf.createLiteral(2));
    con.add(vf.createIRI("http://whatever/b"), vf.createIRI("http://whatever/attrib"), vf.createLiteral("muhehe"));
    String serql = "SELECT higher FROM {node} <http://whatever/val> {higher} WHERE higher > ANY (SELECT value FROM {} <http://whatever/val> {value})";
    TupleQueryResult res = con.prepareTupleQuery(QueryLanguage.SERQL, serql).evaluate();
    assertTrue(res.hasNext());
    assertEquals(2, ((Literal) res.next().getValue("higher")).intValue());
    serql = "SELECT lower FROM {node} <http://whatever/val> {lower} WHERE lower < ANY (SELECT value FROM {} <http://whatever/val> {value})";
    res = con.prepareTupleQuery(QueryLanguage.SERQL, serql).evaluate();
    assertTrue(res.hasNext());
    assertEquals(1, ((Literal) res.next().getValue("lower")).intValue());
    con.add(vf.createBNode("http://whatever/c"), vf.createIRI("http://whatever/val"), vf.createLiteral(3));
    serql = "SELECT highest FROM {node} <http://whatever/val> {highest} WHERE highest >= ALL (SELECT value FROM {} <http://whatever/val> {value})";
    res = con.prepareTupleQuery(QueryLanguage.SERQL, serql).evaluate();
    assertTrue(res.hasNext());
    assertEquals(3, ((Literal) res.next().getValue("highest")).intValue());
    serql = "SELECT val FROM {node} <http://whatever/val> {val} WHERE val IN (SELECT value FROM {} <http://whatever/val> {value}; <http://whatever/attrib> {\"muhehe\"})";
    res = con.prepareTupleQuery(QueryLanguage.SERQL, serql).evaluate();
    assertTrue(res.hasNext());
    assertEquals(2, ((Literal) res.next().getValue("val")).intValue());
}
 
Example #9
Source File: ModelsTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testSetPropertyWithContext2() {
	Literal lit1 = VF.createLiteral(1.0);
	IRI graph1 = VF.createIRI("urn:g1");
	IRI graph2 = VF.createIRI("urn:g2");
	model1.add(foo, bar, lit1, graph1);
	model1.add(foo, bar, bar);
	model1.add(foo, bar, foo, graph2);

	Literal lit2 = VF.createLiteral(2.0);

	Model m = Models.setProperty(model1, foo, bar, lit2);

	assertNotNull(m);
	assertEquals(model1, m);
	assertFalse(model1.contains(foo, bar, lit1));
	assertFalse(model1.contains(foo, bar, lit1, graph1));
	assertFalse(model1.contains(foo, bar, foo));
	assertFalse(model1.contains(foo, bar, bar));
	assertFalse(model1.contains(foo, bar, foo, graph2));
	assertTrue(model1.contains(foo, bar, lit2));
}
 
Example #10
Source File: XMLDatatypeMathUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static Literal operationsBetweenDurationAndCalendar(Literal durationLit, Literal calendarLit, MathOp op) {
	Duration duration = XMLDatatypeUtil.parseDuration(durationLit.getLabel());
	XMLGregorianCalendar calendar = (XMLGregorianCalendar) calendarLit.calendarValue().clone();

	try {
		if (op == MathOp.PLUS) {
			// op:add-yearMonthDuration-to-dateTime and op:add-dayTimeDuration-to-dateTime and
			// op:add-yearMonthDuration-to-date and op:add-dayTimeDuration-to-date and
			// op:add-dayTimeDuration-to-time
			calendar.add(duration);
			return SimpleValueFactory.getInstance().createLiteral(calendar);
		} else {
			throw new ValueExprEvaluationException(
					"Only addition is defined between xsd:duration and calendar datatypes.");
		}
	} catch (IllegalStateException e) {
		throw new ValueExprEvaluationException(e);
	}
}
 
Example #11
Source File: SfWithinTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Test sfWithin
 *
 * @throws IOException
 */
@Test
public void testDenverSfWithinColorado() throws IOException {
	BindingSet bs = GeoSPARQLTests.getBindingSet("sfwithin_denver.rq");

	assertNotNull("Bindingset is null", bs);

	Value value = bs.getBinding("within").getValue();
	assertNotNull("Binded value is null", value);

	assertTrue("Value is not a literal", value instanceof Literal);
	Literal l = (Literal) value;
	assertTrue("Literal not of type double", l.getDatatype().equals(XMLSchema.BOOLEAN));

	assertTrue("Denver not within Colorado", l.booleanValue());
}
 
Example #12
Source File: GeoParseUtils.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Parse GML/wkt literal to Geometry
 *
 * @param statement
 * @return
 * @throws ParseException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
public static Geometry getGeometry(final Statement statement, GmlToGeometryParser gmlToGeometryParser) throws ParseException {
    // handle GML or WKT
    final Literal lit = getLiteral(statement);
    if (GeoConstants.XMLSCHEMA_OGC_WKT.equals(lit.getDatatype())) {
        final String wkt = lit.getLabel().toString();
        return (new WKTReader()).read(wkt);
    } else if (GeoConstants.XMLSCHEMA_OGC_GML.equals(lit.getDatatype())) {
        final String gml = lit.getLabel().toString();
        try {
            return getGeometryGml(gml, gmlToGeometryParser);
        } catch (IOException | SAXException | ParserConfigurationException e) {
            throw new ParseException(e);
        }
    } else {
        throw new ParseException("Literal is unknown geo type, expecting WKT or GML: " + statement.toString());
    }
}
 
Example #13
Source File: FileIO.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void writeValue(Value value, DataOutputStream dataOut) throws IOException {
	if (value instanceof IRI) {
		dataOut.writeByte(URI_MARKER);
		writeString(((IRI) value).toString(), dataOut);
	} else if (value instanceof BNode) {
		dataOut.writeByte(BNODE_MARKER);
		writeString(((BNode) value).getID(), dataOut);
	} else if (value instanceof Literal) {
		Literal lit = (Literal) value;

		String label = lit.getLabel();
		IRI datatype = lit.getDatatype();

		if (Literals.isLanguageLiteral(lit)) {
			dataOut.writeByte(LANG_LITERAL_MARKER);
			writeString(label, dataOut);
			writeString(lit.getLanguage().get(), dataOut);
		} else {
			dataOut.writeByte(DATATYPE_LITERAL_MARKER);
			writeString(label, dataOut);
			writeValue(datatype, dataOut);
		}
	} else {
		throw new IllegalArgumentException("unexpected value type: " + value.getClass());
	}
}
 
Example #14
Source File: XMLDatatypeMathUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static Literal operationsBetweenDurations(Literal leftLit, Literal rightLit, MathOp op) {
	Duration left = XMLDatatypeUtil.parseDuration(leftLit.getLabel());
	Duration right = XMLDatatypeUtil.parseDuration(rightLit.getLabel());
	try {
		switch (op) {
		case PLUS:
			// op:add-yearMonthDurations and op:add-dayTimeDurations
			return buildLiteral(left.add(right));
		case MINUS:
			// op:subtract-yearMonthDurations and op:subtract-dayTimeDurations
			return buildLiteral(left.subtract(right));
		case MULTIPLY:
			throw new ValueExprEvaluationException("Multiplication is not defined on xsd:duration.");
		case DIVIDE:
			throw new ValueExprEvaluationException("Division is not defined on xsd:duration.");
		default:
			throw new IllegalArgumentException("Unknown operator: " + op);
		}
	} catch (IllegalStateException e) {
		throw new ValueExprEvaluationException(e);
	}
}
 
Example #15
Source File: DistanceTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Test distance between two cities, in meters.
 *
 * @throws IOException
 */
@Test
public void testDistanceAmBxl() throws IOException {
	BindingSet bs = GeoSPARQLTests.getBindingSet("distance.rq");

	assertNotNull("Bindingset is null", bs);

	Value value = bs.getBinding("dist").getValue();
	assertNotNull("Binded value is null", value);

	assertTrue("Value is not a literal", value instanceof Literal);
	Literal l = (Literal) value;
	assertTrue("Literal not of type double", l.getDatatype().equals(XMLSchema.DOUBLE));

	assertEquals("Distance Amsterdam-Brussels not correct", 173, l.doubleValue() / 1000, 0.5);
}
 
Example #16
Source File: StrDt.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException {
	if (args.length != 2) {
		throw new ValueExprEvaluationException("STRDT requires 2 arguments, got " + args.length);
	}

	Value lexicalValue = args[0];
	Value datatypeValue = args[1];

	if (QueryEvaluationUtil.isSimpleLiteral(lexicalValue)) {
		Literal lit = (Literal) lexicalValue;
		if (datatypeValue instanceof IRI) {
			return valueFactory.createLiteral(lit.getLabel(), (IRI) datatypeValue);
		} else {
			throw new ValueExprEvaluationException("illegal value for operand: " + datatypeValue);
		}
	} else {
		throw new ValueExprEvaluationException("illegal value for operand: " + lexicalValue);
	}
}
 
Example #17
Source File: XMLDatatypeMathUtilTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testCompute() throws Exception {
	Literal float1 = vf.createLiteral("12", XMLSchema.INTEGER);
	Literal float2 = vf.createLiteral("2", XMLSchema.INTEGER);
	Literal duration1 = vf.createLiteral("P1Y1M", XMLSchema.YEARMONTHDURATION);
	Literal duration2 = vf.createLiteral("P1Y", XMLSchema.YEARMONTHDURATION);
	Literal yearMonth1 = vf.createLiteral("2012-10", XMLSchema.GYEARMONTH);

	assertComputeEquals(vf.createLiteral("14", XMLSchema.INTEGER), float1, float2, MathOp.PLUS);
	assertComputeEquals(vf.createLiteral("10", XMLSchema.INTEGER), float1, float2, MathOp.MINUS);
	assertComputeEquals(vf.createLiteral("24", XMLSchema.INTEGER), float1, float2, MathOp.MULTIPLY);
	assertComputeEquals(vf.createLiteral("6", XMLSchema.DECIMAL), float1, float2, MathOp.DIVIDE);

	assertComputeEquals(vf.createLiteral("P2Y1M", XMLSchema.YEARMONTHDURATION), duration1, duration2, MathOp.PLUS);
	assertComputeEquals(vf.createLiteral("P0Y1M", XMLSchema.YEARMONTHDURATION), duration1, duration2, MathOp.MINUS);

	assertComputeEquals(vf.createLiteral("P12Y", XMLSchema.YEARMONTHDURATION), float1, duration2, MathOp.MULTIPLY);
	assertComputeEquals(vf.createLiteral("P12Y", XMLSchema.YEARMONTHDURATION), duration2, float1, MathOp.MULTIPLY);

	assertComputeEquals(vf.createLiteral("2013-11", XMLSchema.GYEARMONTH), yearMonth1, duration1, MathOp.PLUS);
	assertComputeEquals(vf.createLiteral("2011-09", XMLSchema.GYEARMONTH), yearMonth1, duration1, MathOp.MINUS);
	assertComputeEquals(vf.createLiteral("2013-11", XMLSchema.GYEARMONTH), duration1, yearMonth1, MathOp.PLUS);
}
 
Example #18
Source File: RandTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testEvaluate() {
	try {
		Literal random = rand.evaluate(f);

		assertNotNull(random);
		assertEquals(XMLSchema.DOUBLE, random.getDatatype());

		double randomValue = random.doubleValue();

		assertTrue(randomValue >= 0.0d);
		assertTrue(randomValue < 1.0d);
	} catch (ValueExprEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}
}
 
Example #19
Source File: StrBeforeTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testEvaluate4a() {

	Literal leftArg = f.createLiteral("foobar");
	Literal rightArg = f.createLiteral("b", XMLSchema.STRING);

	try {
		Literal result = strBeforeFunc.evaluate(f, leftArg, rightArg);

		assertEquals("foo", result.getLabel());
		assertEquals(XMLSchema.STRING, result.getDatatype());

	} catch (ValueExprEvaluationException e) {
		fail(e.getMessage());
	}
}
 
Example #20
Source File: SPARQLQueryStringUtil.java    From semagrow with Apache License 2.0 6 votes vote down vote up
/**
 * Append the literal to the stringbuilder: "myLiteral"^^<dataType>
 *
 * @param sb
 * @param lit
 * @return the StringBuilder, for convenience
 */
private static StringBuilder appendLiteral(StringBuilder sb, Literal lit)
{
    sb.append('"');
    sb.append(lit.getLabel().replace("\"", "\\\""));
    sb.append('"');

    //if (Literals.isLanguageLiteral(lit)) {
    //    sb.append('@');
    //    sb.append(lit.getLanguage());
    // }
    //else {
    if (lit.getDatatype() != null) {
        sb.append("^^<");
        sb.append(lit.getDatatype().stringValue());
        sb.append('>');
    }
    //}
    return sb;
}
 
Example #21
Source File: RdfCloudTripleStoreConnectionTest.java    From rya with Apache License 2.0 6 votes vote down vote up
public void testPOObjRange() throws Exception {
    RepositoryConnection conn = repository.getConnection();
    IRI loadPerc = VF.createIRI(litdupsNS, "loadPerc");
    Literal six = VF.createLiteral("6");
    Literal sev = VF.createLiteral("7");
    Literal ten = VF.createLiteral("10");
    conn.add(cpu, loadPerc, six);
    conn.add(cpu, loadPerc, sev);
    conn.add(cpu, loadPerc, ten);
    conn.commit();

    String query = "PREFIX org.apache: <" + NAMESPACE + ">\n" +
            "select * where {" +
            "?x <" + loadPerc.stringValue() + "> ?o.\n" +
            "FILTER(org.apache:range(?o, '6', '8'))." +
            "}";
    TupleQuery tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
    CountTupleHandler cth = new CountTupleHandler();
    tupleQuery.evaluate(cth);
    conn.close();
    assertEquals(2, cth.getCount());
}
 
Example #22
Source File: LastIndexOf.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Value evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException {
	if (args.length < 2 || args.length > 3) {
		throw new ValueExprEvaluationException("Incorrect number of arguments");
	}
	if (!(args[0] instanceof Literal)) {
		throw new ValueExprEvaluationException("First argument must be a string");
	}
	if (!(args[1] instanceof Literal)) {
		throw new ValueExprEvaluationException("Second argument must be a string");
	}
	if (args.length == 3 && !(args[2] instanceof Literal)) {
		throw new ValueExprEvaluationException("Third argument must be an integer");
	}
	Literal s = (Literal) args[0];
	Literal t = (Literal) args[1];
	int pos = (args.length == 3) ? ((Literal) args[2]).intValue() : s.getLabel().length();
	int index = s.getLabel().lastIndexOf(t.getLabel(), pos);
	if (index == -1) {
		throw new ValueExprEvaluationException("Substring not found");
	}
	return valueFactory.createLiteral(index);
}
 
Example #23
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testInComparison3() throws Exception {
	loadTestData("/testdata-query/dataset-ses1913.trig");
	StringBuilder query = new StringBuilder();
	query.append(" PREFIX : <http://example.org/>\n");
	query.append(" SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1, 1/0)) } ");

	TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query.toString());

	try (TupleQueryResult result = tq.evaluate();) {
		assertNotNull(result);
		assertTrue(result.hasNext());

		BindingSet bs = result.next();
		Value y = bs.getValue("y");
		assertNotNull(y);
		assertTrue(y instanceof Literal);
		assertEquals(f.createLiteral("1", XMLSchema.INTEGER), y);
	}
}
 
Example #24
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testInComparison1() throws Exception {
	loadTestData("/testdata-query/dataset-ses1913.trig");
	StringBuilder query = new StringBuilder();
	query.append(" PREFIX : <http://example.org/>\n");
	query.append(" SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1/0 , 1)) } ");

	TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query.toString());

	try (TupleQueryResult result = tq.evaluate();) {
		assertNotNull(result);
		assertTrue(result.hasNext());

		BindingSet bs = result.next();
		Value y = bs.getValue("y");
		assertNotNull(y);
		assertTrue(y instanceof Literal);
		assertEquals(f.createLiteral("1", XMLSchema.INTEGER), y);
	}
}
 
Example #25
Source File: LuceneSpinSailConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void statementAdded(Statement statement) {
	// we only consider statements that contain literals
	if (statement.getObject() instanceof Literal) {

		statement = sail.mapStatement(statement);

		// process only mapped/indexable statements
		if (statement == null) {
			return;
		}

		// we further only index statements where the Literal's datatype is
		// accepted
		Literal literal = (Literal) statement.getObject();
		if (luceneIndex.accept(literal)) {
			buffer.add(statement);
		}
	}
}
 
Example #26
Source File: QueryStringUtilTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testLanguageLiteral() {
	Literal literal = VF.createLiteral("lang \"literal\"", "en");

	assertEquals("\"lang \\\"literal\\\"\"@en", QueryStringUtil.valueToString(literal));
	assertEquals("\"lang \\\"literal\\\"\"@en", valueToStringWithStringBuilder(literal));
}
 
Example #27
Source File: RDFStarUtilTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testDecoding() {
	IRI iri = vf.createIRI("urn:a");
	assertSame(iri, RDFStarUtil.fromRDFEncodedValue(iri));

	Literal literal1 = vf.createLiteral("plain");
	assertSame(literal1, RDFStarUtil.fromRDFEncodedValue(literal1));
	assertFalse(RDFStarUtil.isEncodedTriple(literal1));

	Literal literal2 = vf.createLiteral(1984L);
	assertSame(literal2, RDFStarUtil.fromRDFEncodedValue(literal2));

	Literal literal3 = vf.createLiteral("einfach aber auf deutsch", "de");
	assertSame(literal3, RDFStarUtil.fromRDFEncodedValue(literal3));
	assertFalse(RDFStarUtil.isEncodedTriple(literal3));

	BNode bNode = vf.createBNode("bnode1");
	assertSame(bNode, RDFStarUtil.fromRDFEncodedValue(bNode));

	IRI encoded = vf.createIRI("urn:rdf4j:triple:PDw8dXJuOmE-IDxodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1ze"
			+ "W50YXgtbnMjdHlwZT4gInBsYWluIj4-");
	Value decoded = RDFStarUtil.fromRDFEncodedValue(encoded);
	assertTrue(decoded instanceof Triple);
	assertEquals(iri, ((Triple) decoded).getSubject());
	assertEquals(RDF.TYPE, ((Triple) decoded).getPredicate());
	assertEquals(literal1, ((Triple) decoded).getObject());
}
 
Example #28
Source File: BufferTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void resultIsPolygonWKT() {
	Literal result = (Literal) buffer.evaluate(f, point, f.createLiteral(1), unit);
	assertNotNull(result);
	assertThat(result.getDatatype()).isEqualTo(GEO.WKT_LITERAL);
	assertThat(result.getLabel()).startsWith("POLYGON ((23.708505");
}
 
Example #29
Source File: NodeKindFilter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
boolean checkTuple(Tuple t) {

	Value value = t.line.get(1);
	/*
	 * BlankNode(SHACL.BLANK_NODE), IRI(SHACL.IRI), Literal(SHACL.LITERAL), BlankNodeOrIRI(SHACL.BLANK_NODE_OR_IRI),
	 * BlankNodeOrLiteral(SHACL.BLANK_NODE_OR_LITERAL), IRIOrLiteral(SHACL.IRI_OR_LITERAL),
	 */

	switch (nodeKind) {
	case IRI:
		return value instanceof IRI;
	case Literal:
		return value instanceof Literal;
	case BlankNode:
		return value instanceof BNode;
	case IRIOrLiteral:
		return value instanceof IRI || value instanceof Literal;
	case BlankNodeOrIRI:
		return value instanceof BNode || value instanceof IRI;
	case BlankNodeOrLiteral:
		return value instanceof BNode || value instanceof Literal;
	}

	throw new IllegalStateException("Unknown nodeKind");

}
 
Example #30
Source File: PrepareOwnedTupleExpr.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void writeLiteral(StringBuilder builder, Literal lit) {
	String label = lit.getLabel();

	if (label.indexOf('\n') > 0 || label.indexOf('\r') > 0 || label.indexOf('\t') > 0) {
		// Write label as long string
		builder.append("\"\"\"");
		builder.append(TurtleUtil.encodeLongString(label));
		builder.append("\"\"\"");
	} else {
		// Write label as normal string
		builder.append("\"");
		builder.append(TurtleUtil.encodeString(label));
		builder.append("\"");
	}

	IRI datatype = lit.getDatatype();
	if (Literals.isLanguageLiteral(lit)) {
		// Append the literal's language
		builder.append("@");
		builder.append(lit.getLanguage().get());
	} else {
		// Append the literal's data type (possibly written as an
		// abbreviated URI)
		builder.append("^^");
		writeURI(builder, datatype);
	}
}