org.openrdf.model.Literal Java Examples

The following examples show how to use org.openrdf.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: RangeQueriesTest.java    From cumulusrdf with Apache License 2.0 6 votes vote down vote up
@Test
public void inverseValueOrderSubjTest() throws CumulusStoreException {

	Value[] query = new Value[2];
	query[0] = buildResource(_subject);
	query[1] = buildResource(_predicate);
	Iterator<Statement> iter = _tripleStore.range(query, null, true, null, true, true, Integer.MAX_VALUE);
	assertTrue(iter != null && iter.hasNext());

	double last = Double.MAX_VALUE;
	double current = Double.MAX_VALUE;
	while (iter.hasNext()) {
		last = current;
		final Statement res = iter.next();
		Literal lit = (Literal) res.getObject();
		current = Double.parseDouble(lit.getLabel());
		assertTrue(last >= current);
	}
}
 
Example #2
Source File: TestSparqlUpdate.java    From database with GNU General Public License v2.0 6 votes vote down vote up
/** @since openrdf 2.6.3 */
public void testDeleteInsertWhereLoopingBehavior() throws Exception {
    log.debug("executing test testDeleteInsertWhereLoopingBehavior");
    final StringBuilder update = new StringBuilder();
    update.append(getNamespaceDeclarations());
    update.append(" DELETE { ?x ex:age ?y } INSERT {?x ex:age ?z }");
    update.append(" WHERE { ");
    update.append("   ?x ex:age ?y .");
    update.append("   BIND((?y + 1) as ?z) ");
    update.append("   FILTER( ?y < 46 ) ");
    update.append(" } ");

    final URI age = f.createURI(EX_NS, "age");
    final Literal originalAgeValue = f.createLiteral("42", XMLSchema.INTEGER);
    final Literal correctAgeValue = f.createLiteral("43", XMLSchema.INTEGER);
    final Literal inCorrectAgeValue = f.createLiteral("46", XMLSchema.INTEGER);

    assertTrue(hasStatement(bob, age, originalAgeValue, true));

    m_repo.prepareUpdate(update.toString()).evaluate();

    assertFalse(hasStatement(bob, age, originalAgeValue, true));
    assertTrue(hasStatement(bob, age, correctAgeValue, true));
    assertFalse(hasStatement(bob, age, inCorrectAgeValue, true));
}
 
Example #3
Source File: CRUDServletPutTest.java    From cumulusrdf with Apache License 2.0 6 votes vote down vote up
/**
 * If the old triple is a constant and it doesn't match anything then the new triple will be applied.
 * 
 * 
 * @throws Exception hopefully never, otherwise the test fails.
 */
@Test
public void putWithOneUnmatchingTriple() throws Exception {
	final URI unexistentSubject = buildResource(randomString());
	final URI unexistentPredicate = buildResource(randomString());
	final Literal unexistentObject = buildLiteral(randomString());
	
	final Literal unexistentNewObject = buildLiteral(randomString());
	
	final Value[] pattern = new Value[]{unexistentSubject, unexistentPredicate, unexistentObject};
	assertEquals(0, numOfRes(TRIPLE_STORE.query(pattern)));
	
	final HttpServletResponse response = mock(HttpServletResponse.class);
	final HttpServletRequest request = createMockHttpRequest(
			unexistentSubject, unexistentPredicate, unexistentObject, 
			null, null, null, unexistentNewObject, null);
	
	_classUnderTest.doPut(request, response);

	assertEquals(0, numOfRes(TRIPLE_STORE.query(pattern)));
	assertEquals(1, numOfRes(TRIPLE_STORE.query(new Value[]{unexistentSubject, unexistentPredicate, unexistentNewObject})));
}
 
Example #4
Source File: BigdataNTriplesParser.java    From database with GNU General Public License v2.0 6 votes vote down vote up
protected Literal createLiteral(String label, String lang, String datatype)
	throws RDFParseException
{
	try {
		label = NTriplesUtil.unescapeString(label);
	}
	catch (IllegalArgumentException e) {
	    reportFatalError(e.getMessage());
	}

	if (lang.length() == 0) {
		lang = null;
	}

	if (datatype.length() == 0) {
		datatype = null;
	}

	URI dtURI = null;
	if (datatype != null) {
		dtURI = createURI(datatype);
	}

	return super.createLiteral(label, lang, dtURI);
}
 
Example #5
Source File: TripleStore.java    From cumulusrdf with Apache License 2.0 6 votes vote down vote up
@Override
public Iterator<byte[][]> rangeDateTimeAsIDs(
		final Value[] query,
		final Literal lower,
		final boolean equalsLower,
		final Literal upper,
		final boolean equalsUpper,
		final boolean reverse,
		final int limit) throws DataAccessLayerException {

	if (query == null || query.length != 2 || isVariable(query[1])) {
		return Iterators.emptyIterator();
	}

	final long lowerBound = lower == null ? Long.MIN_VALUE : Util.parseXMLSchemaDateTimeAsMSecs(lower), upperBound = upper == null ? Long.MAX_VALUE
			: Util.parseXMLSchemaDateTimeAsMSecs(upper);

	return _rdfIndexDAO.dateRangeQuery(query, lowerBound, equalsLower, upperBound, equalsUpper, reverse, limit);
}
 
Example #6
Source File: TestCustomFunction.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Override
public IV get(final IBindingSet bset) {

    // Evaluate a function argument.
    final IV arg = getAndCheckLiteral(0, bset);
    
    // Convert into an RDF Value.
    final Literal lit = asLiteral(arg);

    // Concat with self.
    final Literal lit2 = new LiteralImpl(lit.getLabel() + "-"
            + lit.getLabel());
    
    // Convert into an IV.
    final IV ret = asIV(lit2, bset);
    
    // Return the function result.
    return ret;

}
 
Example #7
Source File: SPARQLUpdateTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testInsertWhereWithBindings()
	throws Exception
{
	logger.debug("executing test testInsertWhereWithBindings");
	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());
	update.append("INSERT { ?x rdfs:comment ?z . } WHERE { ?x foaf:name ?y }");

	Literal comment = f.createLiteral("Bob has a comment");

	Update operation = con.prepareUpdate(QueryLanguage.SPARQL, update.toString());
	operation.setBinding("x", bob);
	operation.setBinding("z", comment);

	assertFalse(con.hasStatement(null, RDFS.COMMENT, comment, true));

	operation.execute();

	assertTrue(con.hasStatement(bob, RDFS.COMMENT, comment, true));
	assertFalse(con.hasStatement(alice, RDFS.COMMENT, comment, true));

}
 
Example #8
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 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());

	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 #9
Source File: LiteralTest.java    From anno4j with Apache License 2.0 6 votes vote down vote up
public void testDateTimeMS() throws Exception {
	TestConcept tester = manager.addDesignation(manager.getObjectFactory().createObject(), TestConcept.class);
	Resource bNode = (Resource) manager.addObject(tester);
	Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
	cal.set(2001, 6, 4, 12, 8, 56);
	cal.set(Calendar.MILLISECOND, 27);
	cal.set(Calendar.ZONE_OFFSET, -7 * 60 * 60 * 1000);
	try {
		Literal literal = getValueFactory().createLiteral(
				"2001-07-04T12:08:56.027-07:00", XMLSchema.DATETIME);
		manager.add(bNode, dateURI, literal);
	} catch (RepositoryException e) {
		throw new ObjectPersistException(e);
	}
	Date date = tester.getADate();
	assertEquals(cal.getTime(), date);
}
 
Example #10
Source File: CRUDServletPutTest.java    From cumulusrdf with Apache License 2.0 6 votes vote down vote up
/**
 * If the old triple is a constant and it doesn't match anything then a new triple will be created.
 * In this first scenario the new triple pattern is not valorized...so that means the old (unexistent triple) 
 * will be created.
 * 
 * @throws Exception hopefully never, otherwise the test fails.
 */
@Test
public void putWithOneUnmatchingTripleAndNoNewTriple() throws Exception {
	final URI unexistentSubject = buildResource(randomString());
	final URI unexistentPredicate = buildResource(randomString());
	final Literal unexistentObject = buildLiteral(randomString());
	
	final Value[] pattern = new Value[]{unexistentSubject, unexistentPredicate, unexistentObject};
	assertEquals(0, numOfRes(TRIPLE_STORE.query(pattern)));
	
	final HttpServletResponse response = mock(HttpServletResponse.class);
	final HttpServletRequest request = createMockHttpRequest(
			unexistentSubject, unexistentPredicate, unexistentObject, 
			null, null, null, null, null);
	
	_classUnderTest.doPut(request, response);

	assertEquals(1, numOfRes(TRIPLE_STORE.query(pattern)));
}
 
Example #11
Source File: TestSparqlUpdate.java    From database with GNU General Public License v2.0 6 votes vote down vote up
public void testReallyLongQueryString()
      throws Exception
  {
final Literal l = getReallyLongLiteral(1000);
    	
      log.debug("executing test testInsertEmptyWhere");
      final StringBuilder update = new StringBuilder();
      update.append(getNamespaceDeclarations());
      update.append("INSERT { <" + bob + "> rdfs:label " + l + " . } WHERE { }");

      assertFalse(hasStatement(bob, RDFS.LABEL, l, true));

      m_repo.prepareUpdate(update.toString()).evaluate();

      assertTrue(hasStatement(bob, RDFS.LABEL, l, true));
  }
 
Example #12
Source File: BlazeGraph.java    From tinkerpop3 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Helper for {@link BlazeEdge#property(String, Object)} and 
 * {@link BlazeVertexProperty#property(String, Object)}.
 * 
 * @param element the BlazeEdge or BlazeVertexProperty
 * @param key the property key
 * @param val the property value
 * @return a BlazeProperty
 */
<V> BlazeProperty<V> property(final BlazeReifiedElement element, 
        final String key, final V val) {
    final BigdataValueFactory rdfvf = rdfValueFactory();
    final BigdataBNode s = element.rdfId();
    final URI p = rdfvf.asValue(vf.propertyURI(key));
    final Literal lit = rdfvf.asValue(vf.toLiteral(val));
    
    final RepositoryConnection cxn = cxn();
    Code.wrapThrow(() -> {
        final BigdataStatement stmt = rdfvf.createStatement(s, p, lit);
        if (!bulkLoad) {
            // remove (<<stmt>> <key> ?)
            cxn.remove(s, p, null);
        }
        // add (<<stmt>> <key> "val")
        cxn.add(stmt);
    });
    
    final BlazeProperty<V> prop = new BlazeProperty<V>(this, element, p, lit);
    return prop;
}
 
Example #13
Source File: BlazeValueFactory.java    From tinkerpop3 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a blueprints property value from a datatyped literal.
 * <p>
 * Return a graph property from a datatyped literal using its
 * XSD datatype.
 * <p>
 * Supports: Float, Double, Integer, Long, Boolean, Short, Byte, and String.
 */
default Object fromLiteral(final Literal l) {
    
    final URI datatype = l.getDatatype();
    
    if (datatype == null) {
        return l.getLabel();
    } else if (datatype.equals(XSD.FLOAT)) {
        return l.floatValue();
    } else if (datatype.equals(XSD.DOUBLE)) {
        return l.doubleValue();
    } else if (datatype.equals(XSD.INT)) {
        return l.intValue();
    } else if (datatype.equals(XSD.LONG)) {
        return l.longValue();
    } else if (datatype.equals(XSD.BOOLEAN)) {
        return l.booleanValue();
    } else if (datatype.equals(XSD.SHORT)) {
        return l.shortValue();
    } else if (datatype.equals(XSD.BYTE)) {
        return l.byteValue();
    } else {
        return l.getLabel();
    }
    
}
 
Example #14
Source File: StrlangBOp.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Override
public IV get(final IBindingSet bs) throws SparqlTypeErrorException {

    final Literal lit = getAndCheckLiteralValue(0, bs);
    
    if (lit.getDatatype() != null || lit.getLanguage() != null) {
        throw new SparqlTypeErrorException();
    }

    final Literal l = getAndCheckLiteralValue(1, bs);
    String label = lit.getLabel();
    String langLit = l.getLabel();
    final BigdataLiteral str = getValueFactory().createLiteral(label, langLit);
    return super.asIV(str, bs);

}
 
Example #15
Source File: ListIndexExtension.java    From tinkerpop3 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Convert the supplied value into an internal representation as
 * PackedLongIV.
 */
@SuppressWarnings("unchecked")
public LiteralExtensionIV createIV(final Value value) {

    if (value instanceof Literal == false)
        throw new IllegalArgumentException();

    final Literal lit = (Literal) value;

    final AbstractLiteralIV delegate = 
            new PackedLongIV(Long.parseLong(lit.getLabel()));
    return new LiteralExtensionIV(delegate, datatype.getIV());

}
 
Example #16
Source File: GraphImpl.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
void add(Resource subject, URI predicate, Value object) {
	if(object instanceof Literal) {
		getOrCreateIndividual(subject).addAssertion(predicate, (Literal)object);
	} else {
		IndividualImpl target = getOrCreateIndividual(subject);
		IndividualImpl linked = getOrCreateIndividual((Resource)object);
		target.addLink(predicate, linked);
	}
	collectNamespace(subject);
	collectNamespace(predicate);
	collectNamespace(object);
}
 
Example #17
Source File: BlazeGraph.java    From tinkerpop3 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Binding set to property (for Edge and VertexProperty elements).
 */
private final <V> Function<BindingSet, Property<V>> 
property(final BlazeReifiedElement e) {
    return bs -> {
        
        log.debug(() -> bs);
        final URI key = (URI) bs.getValue("key");
        final Literal val = (Literal) bs.getValue("val");
        final BlazeProperty<V> prop = 
                new BlazeProperty<>(BlazeGraph.this, e, key, val);
        return prop;
        
    };
}
 
Example #18
Source File: BlazeProperty.java    From tinkerpop3 with GNU General Public License v2.0 5 votes vote down vote up
BlazeProperty(final BlazeGraph graph, final BlazeElement element,
        final URI key, final Literal val) {
    this.graph = graph;
    this.vf = graph.valueFactory();
    this.element = element;
    this.key = key;
    this.val = val;
}
 
Example #19
Source File: RDFStoreTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testValueRoundTrip3()
	throws Exception
{
	URI subj = new URIImpl(EXAMPLE_NS + PICASSO);
	URI pred = new URIImpl(EXAMPLE_NS + PAINTS);
	Literal obj = new LiteralImpl("guernica");

	testValueRoundTrip(subj, pred, obj);
}
 
Example #20
Source File: IriBOp.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Override
    public IV get(final IBindingSet bs) throws SparqlTypeErrorException {
        
    	final IV iv = getAndCheckBound(0, bs);

        if (iv.isURI()) {
        	return iv;
        }

        if (!iv.isLiteral())
            throw new SparqlTypeErrorException();

        final String baseURI = getProperty(Annotations.BASE_URI, "");
        
        final Literal lit = asLiteral(iv);

        final URI dt = lit.getDatatype();

        if (dt != null && !dt.stringValue().equals(XSD.STRING.stringValue()))
            throw new SparqlTypeErrorException();

//        final BigdataURI uri = getValueFactory().createURI(baseURI+lit.getLabel());

        BigdataURI uri = null;
        try {
            uri = getValueFactory().createURI(lit.getLabel());
        }
        catch (IllegalArgumentException e) {
            try {
                uri = getValueFactory().createURI(baseURI, lit.getLabel());
            }
            catch (IllegalArgumentException e1) {
                throw new SparqlTypeErrorException();
            }
        }

        return super.asIV(uri, bs);

    }
 
Example #21
Source File: QNameMarshall.java    From anno4j with Apache License 2.0 5 votes vote down vote up
public Literal serialize(QName object) {
	if (object.getPrefix().length() == 0)
		return vf.createLiteral(object.toString());
	StringBuilder label = new StringBuilder();
	label.append(object.getPrefix());
	label.append(":");
	label.append(object.getLocalPart());
	return vf.createLiteral(label.toString());
}
 
Example #22
Source File: ObjectConstructorMarshall.java    From anno4j with Apache License 2.0 5 votes vote down vote up
public T deserialize(Literal literal) {
	try {
		return constructor.newInstance(new Object[] { literal.getLabel() });
	} catch (Exception e) {
		throw new ObjectConversionException(e);
	}
}
 
Example #23
Source File: RangeStatementPattern.java    From cumulusrdf with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a statement pattern that matches a subject-, predicate- and
 * object variable against statements from all contexts.
 */
public RangeStatementPattern(Var subject, Var predicate, Var object, Literal lowerBound, boolean equal_lower, Literal upperBound,
		boolean equal_upper, Literal equals) {

	super(Scope.DEFAULT_CONTEXTS, subject, predicate, object);

	_lowerBound = lowerBound;
	_upperBound = upperBound;

	_equals = equals;

	_equal_lower = equal_lower;
	_equal_upper = equal_upper;
}
 
Example #24
Source File: SqlTimestampMarshall.java    From anno4j with Apache License 2.0 5 votes vote down vote up
public Literal serialize(Timestamp object) {
	GregorianCalendar gc = new GregorianCalendar(0, 0, 0);
	gc.setTime(object);
	XMLGregorianCalendar xgc = factory.newXMLGregorianCalendar(gc);
	BigDecimal fraction = BigDecimal.valueOf(object.getNanos(), 9);
	xgc.setFractionalSecond(fraction);
	String label = xgc.toXMLFormat();
	return vf.createLiteral(label, datatype);
}
 
Example #25
Source File: SparqlBuilder.java    From database with GNU General Public License v2.0 5 votes vote down vote up
public Graph addTriplePattern(String s, String p, Value o) {
    Triple triple =
            new Triple(s, p, o instanceof URI ? uri((URI) o)
                    : literal((Literal) o));
    add(triple);
    return this;
}
 
Example #26
Source File: BigdataComplexSparqlQueryTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * TODO Write optimizer to pull this BindingsClause out of the join
 * group and make it global.
 */
public void testRequiredValues() throws Exception {
    loadTestData("/testdata-query/dataset-ses1692.trig");
    StringBuilder query = new StringBuilder();
    query.append(" PREFIX : <http://example.org/>\n");
    query.append(" SELECT DISTINCT ?a ?name ?isX WHERE { ?b :p1 ?a . ?a :name ?name. ?a a :X . VALUES(?isX) { (:X) } } ");

    BigdataSailTupleQuery tq = (BigdataSailTupleQuery)
            conn.prepareTupleQuery(QueryLanguage.SPARQL, query.toString());
    
    if (logger.isInfoEnabled()) {
        logger.info("optimized ast:\n"+tq.optimize());
        logger.info("query plan:\n"+BOpUtility.toString(tq.getASTContainer().getQueryPlan()));
    }

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

    int count = 0;
    while (result.hasNext()) {
        count++;
        BindingSet bs = result.next();
        System.out.println(bs);
        URI a = (URI)bs.getValue("a");
        assertNotNull(a);
        Value isX = bs.getValue("isX");
        Literal name = (Literal)bs.getValue("name");
        assertNotNull(name);
        if (a.stringValue().endsWith("a1")) {
            assertNotNull(isX);
        }
        else if (a.stringValue().endsWith(("a2"))) {
            assertNull(isX);
        }
    }
    assertEquals(1, count);
}
 
Example #27
Source File: ObjectArrayCursor.java    From anno4j with Apache License 2.0 5 votes vote down vote up
private Object createRDFObject(Value value, String binding, List<BindingSet> properties)
		throws QueryEvaluationException {
	if (value == null)
		return null;
	if (value instanceof Literal)
		return of.createObject((Literal) value);
	Object obj;
	if (properties.get(0).hasBinding(binding + "_class")) {
		Set<URI> list = new HashSet<URI>(properties.size());
		for (BindingSet bindings : properties) {
			Value t = bindings.getValue(binding + "_class");
			if (t instanceof URI) {
				list.add((URI) t);
			}
		}
		obj = manager.getObject(list, (Resource) value);
	} else {
		try {
			obj = manager.getObject(value);
		} catch (RepositoryException e) {
			throw new QueryEvaluationException(e);
		}
	}
	if (obj instanceof PropertyConsumer) {
		((PropertyConsumer) obj).usePropertyBindings(binding, properties);
	}
	return obj;
}
 
Example #28
Source File: TestRDRHistory.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test whether the RDRHistory can handle statements that are added
 * and removed in the same commit.
 */
public void testFullyRedundantEvents() throws Exception {

    BigdataSailRepositoryConnection cxn = null;

    final BigdataSail sail = getSail(getProperties());

    try {

        sail.initialize();
        final BigdataSailRepository repo = new BigdataSailRepository(sail);
        cxn = (BigdataSailRepositoryConnection) repo.getConnection();

        final BigdataValueFactory vf = (BigdataValueFactory) sail
                .getValueFactory();
        final URI s = vf.createURI(":s");
        final URI p = vf.createURI(":p");
        final Literal o = vf.createLiteral("foo");
        final BigdataStatement stmt = vf.createStatement(s, p, o);
        final BigdataBNode sid = vf.createBNode(stmt);

        cxn.add(stmt);
        cxn.commit();

        assertEquals(1, cxn.getTripleStore().getAccessPath(sid, null, null).rangeCount(false));
        
        cxn.remove(stmt);
        cxn.add(stmt);
        cxn.commit();

        assertEquals(1, cxn.getTripleStore().getAccessPath(sid, null, null).rangeCount(false));
                    
    } finally {
        if (cxn != null)
            cxn.close();
        
        sail.__tearDownUnitTest();
    }
}
 
Example #29
Source File: BasicSkin.java    From database with GNU General Public License v2.0 5 votes vote down vote up
public double getDoubleValue(final URI key) {
	final Value v = m_gpo.getValue(key);
	
	if (v instanceof Literal) {
		return ((Literal) v).doubleValue();
	} else {	
		return 0;
	}
}
 
Example #30
Source File: TurtleValueUtils.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
public String toString(Value v) {
	String result=null;
	if(v instanceof URI) {
		result=writeURI((URI)v);
	} else if(v instanceof BNode) {
		result=writeBNode((BNode)v);
	} else if(v instanceof Literal) {
		result=writeLiteral((Literal)v);
	} else {
		throw new IllegalStateException("Unexpected value type "+v.getClass().getCanonicalName());
	}
	return result;
}