Java Code Examples for org.eclipse.rdf4j.model.IRI

The following examples show how to use org.eclipse.rdf4j.model.IRI. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: rya   Source File: RdfCloudTripleStoreConnectionTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testEvaluate() throws Exception {
    RepositoryConnection conn = repository.getConnection();
    IRI loadPerc = VF.createIRI(litdupsNS, "loadPerc");
    IRI uri1 = VF.createIRI(litdupsNS, "uri1");
    conn.add(cpu, loadPerc, uri1);
    conn.commit();

    String query = "select * where {" +
            "?x <" + loadPerc.stringValue() + "> ?o1." +
            "}";
    TupleQuery tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
    CountTupleHandler cth = new CountTupleHandler();
    tupleQuery.evaluate(cth);
    assertEquals(cth.getCount(), 1);
    conn.close();
}
 
Example 2
private long getTriplesCount(IRI subjectNode, long defaultValue) {
    try (CloseableIteration<? extends Statement, SailException> ci = statsConnection.getStatements(subjectNode, VOID.TRIPLES, null, true, HALYARD.STATS_GRAPH_CONTEXT)) {
        if (ci.hasNext()) {
            Value v = ci.next().getObject();
            if (v instanceof Literal) {
                try {
                    long l = ((Literal) v).longValue();
                    LOG.log(Level.FINER, "triple stats for {0} = {1}", new Object[]{subjectNode, l});
                    return l;
                } catch (NumberFormatException ignore) {
                }
            }
            LOG.log(Level.WARNING, "Invalid statistics for:{0}", subjectNode);
        }
    }
    LOG.log(Level.FINER, "triple stats for {0} are not available", subjectNode);
    return defaultValue;
}
 
Example 3
@Test
public void testTupleQuery() throws Exception {
	RepositoryConnection stub = new RepositoryConnectionStub() {

		@Override
		public TupleQuery prepareTupleQuery(QueryLanguage ql, String query, String baseURI)
				throws MalformedQueryException, RepositoryException {
			assertEquals(SPARQL, ql);
			assertEquals(queryString, query);
			return new TupleQueryStub() {

				@Override
				public void setDataset(Dataset dataset) {
					Set<IRI> contexts = Collections.singleton(context);
					assertEquals(contexts, dataset.getDefaultGraphs());
					super.setDataset(dataset);
				}
			};
		}
	};
	Repository repo = stub.getRepository();
	ContextAwareConnection con = new ContextAwareConnection(repo, stub);
	con.setReadContexts(context);
	con.setQueryLanguage(SERQL);
	con.prepareTupleQuery(SPARQL, queryString, null);
}
 
Example 4
@Override
protected double getCardinality(StatementPattern sp) {

	SailDataset dataset = extensibleSailStore.getExplicitSailSource().dataset(IsolationLevels.NONE);

	Resource subject = (Resource) sp.getSubjectVar().getValue();
	IRI predicate = (IRI) sp.getPredicateVar().getValue();
	Value object = sp.getObjectVar().getValue();

	if (sp.getScope() == StatementPattern.Scope.DEFAULT_CONTEXTS) {
		try (Stream<? extends Statement> stream = Iterations
				.stream(dataset.getStatements(subject, predicate, object))) {
			return stream.count();
		}
	} else {
		Resource[] context = new Resource[] { (Resource) sp.getContextVar().getValue() };
		try (Stream<? extends Statement> stream = Iterations
				.stream(dataset.getStatements(subject, predicate, object, context))) {
			return stream.count();
		}
	}

}
 
Example 5
/**
 * Delete data from the graph.
 */
private ModelAndView getDeleteDataResult(Repository repository, HttpServletRequest request,
		HttpServletResponse response) throws ClientHTTPException, ServerHTTPException {
	ProtocolUtil.logRequestParameters(request);

	ValueFactory vf = repository.getValueFactory();

	IRI graph = getGraphName(request, vf);

	try (RepositoryConnection repositoryCon = RepositoryInterceptor.getRepositoryConnection(request)) {
		repositoryCon.clear(graph);

		return new ModelAndView(EmptySuccessView.getInstance());
	} catch (RepositoryException e) {
		throw new ServerHTTPException("Repository update error: " + e.getMessage(), e);
	}
}
 
Example 6
Source Project: rya   Source File: InferenceEngine.java    License: Apache License 2.0 6 votes vote down vote up
private void refreshInverseOf() throws QueryEvaluationException {
    final CloseableIteration<Statement, QueryEvaluationException> iter = RyaDAOHelper.query(ryaDAO, null, OWL.INVERSEOF, null, conf);
    final Map<IRI, IRI> invProp = new HashMap<>();
    try {
        while (iter.hasNext()) {
            final Statement st = iter.next();
            invProp.put((IRI) st.getSubject(), (IRI) st.getObject());
            invProp.put((IRI) st.getObject(), (IRI) st.getSubject());
        }
    } finally {
        if (iter != null) {
            iter.close();
        }
    }
    synchronized(inverseOfMap) {
        inverseOfMap.clear();
        inverseOfMap.putAll(invProp);
    }
}
 
Example 7
private int size(IRI defaultGraph) throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	TupleQuery qry = testCon.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT * { ?s ?p ?o }");
	SimpleDataset dataset = new SimpleDataset();
	dataset.addDefaultGraph(defaultGraph);
	qry.setDataset(dataset);
	TupleQueryResult result = qry.evaluate();
	try {
		int count = 0;
		while (result.hasNext()) {
			result.next();
			count++;
		}
		return count;
	} finally {
		result.close();
	}
}
 
Example 8
@Override
public synchronized boolean remove(Resource subj, IRI pred, Value obj, Resource... contexts) {
	try {
		if (contains(subj, pred, obj, contexts)) {
			size = -1;
			CloseableIteration<? extends Statement, SailException> stmts;
			stmts = dataset().getStatements(subj, pred, obj, contexts);
			try {

				while (stmts.hasNext()) {
					Statement st = stmts.next();

					sink.deprecate(st);
				}

			} finally {
				stmts.close();
			}
			return true;
		}
	} catch (SailException e) {
		throw new ModelException(e);
	}
	return false;
}
 
Example 9
@Override
public void addWithoutCommit(Resource subject, IRI predicate, Value object, Resource... contexts)
		throws RepositoryException {
	boolean reportEvent = activated;

	if (reportEvent && reportDeltas()) {
		// Only report if the statement is not present yet
		reportEvent = !getDelegate().hasStatement(subject, predicate, object, false, contexts);
	}

	getDelegate().add(subject, predicate, object, contexts);

	if (reportEvent) {
		for (RepositoryConnectionListener listener : listeners) {
			listener.add(getDelegate(), subject, predicate, object, contexts);
		}
	}
}
 
Example 10
Source Project: rdf4j   Source File: SpinRenderer.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void meet(ProjectionElem node) throws RDFHandlerException {
	if (isSubQuery) {
		super.meet(node);
	} else {
		String varName = node.getSourceName();
		ValueExpr valueExpr = inlineBindings.getValueExpr(varName);
		Value value = (valueExpr instanceof ValueConstant) ? ((ValueConstant) valueExpr).getValue()
				: getVar(varName);
		String targetName = node.getTargetName();
		IRI pred;
		if ("subject".equals(targetName)) {
			pred = SP.SUBJECT_PROPERTY;
		} else if ("predicate".equals(targetName)) {
			pred = SP.PREDICATE_PROPERTY;
		} else if ("object".equals(targetName)) {
			pred = SP.OBJECT_PROPERTY;
		} else {
			throw new AssertionError("Unexpected ProjectionElem: " + node);
		}
		handler.handleStatement(valueFactory.createStatement(subject, pred, value));
	}
}
 
Example 11
private static List<IRI> retrieveInstances(RepositoryConnection conn, IRI type) throws Exception {

		List<IRI> res = new ArrayList<>();
		RepositoryResult<Statement> qres = null;
		try {
			qres = conn.getStatements(null, RDF.TYPE, type, false);
			while (qres.hasNext() && res.size() < MAX_INSTANCES) {
				Statement next = qres.next();
				res.add((IRI) next.getObject());
			}
		} finally {
			try {
				if (qres != null) {
					qres.close();
				}
			} catch (Exception ignore) {
			}
		}
		return res;
	}
 
Example 12
Source Project: rdf4j   Source File: EhContainsTest.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Test ehContains.
 *
 * @throws IOException
 */
@Test
public void testEhContainsDenver() throws IOException {
	List<BindingSet> list = GeoSPARQLTests.getResults("ehcontains.rq");

	assertNotNull("Resultset is null", list);
	assertEquals("Number of results must be one", 1, list.size());

	Value value = list.get(0).getBinding("city").getValue();
	assertNotNull("Binded value is null", value);

	assertTrue("Value is not an IRI", value instanceof IRI);
	IRI iri = (IRI) value;

	assertEquals("City is not Denver", "http://example.org/denver", iri.stringValue());
}
 
Example 13
Source Project: rya   Source File: GeoTemporalProviderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void twoPatternsTwoFilters_test() throws Exception {
    final ValueFactory vf = SimpleValueFactory.getInstance();
    final Value geo = vf.createLiteral("Point(0 0)", GeoConstants.XMLSCHEMA_OGC_WKT);
    final Value temp = vf.createLiteral(new TemporalInstantRfc3339(2015, 12, 30, 12, 00, 0).toString());
    final IRI tempPred = vf.createIRI(URI_PROPERTY_AT_TIME);
    final String query =
        "PREFIX geo: <http://www.opengis.net/ont/geosparql#>" +
        "PREFIX geos: <http://www.opengis.net/def/function/geosparql/>" +
        "PREFIX time: <tag:rya-rdf.org,2015:temporal#>" +
        "SELECT * WHERE { " +
            "?subj <" + tempPred + "> ?time ."+
            "?subj <" + GeoConstants.GEO_AS_WKT + "> ?loc . " +
            " FILTER(geos:sfContains(?loc, " + geo + ")) . " +
            " FILTER(time:equals(?time, " + temp + ")) . " +
        "}";
    final QuerySegment<EventQueryNode> node = getQueryNode(query);
    final List<EventQueryNode> nodes = provider.getExternalSets(node);
    assertEquals(1, nodes.size());
}
 
Example 14
@Setup(Level.Invocation)
public void setUp() {
	Logger root = (Logger) LoggerFactory.getLogger(ShaclSailConnection.class.getName());
	root.setLevel(ch.qos.logback.classic.Level.INFO);

	SimpleValueFactory vf = SimpleValueFactory.getInstance();

	allStatements = BenchmarkConfigs.generateStatements(((statements, i, j) -> {
		IRI iri = vf.createIRI("http://example.com/" + i + "_" + j);
		statements.add(vf.createStatement(iri, RDF.TYPE, RDFS.RESOURCE));
		statements.add(vf.createStatement(iri, RDFS.LABEL, vf.createLiteral("label" + i)));
	}));

	System.gc();

}
 
Example 15
@Override
public CloseableIteration<Statement, QueryEvaluationException> getStatements(
		Resource subj, IRI pred, Value obj, QueryInfo queryInfo,
		Resource... contexts) throws RepositoryException,
		MalformedQueryException, QueryEvaluationException {

	return withConnection((conn, resultHolder) -> {
		monitorRemoteRequest();
		RepositoryResult<Statement> repoResult = conn.getStatements(subj, pred, obj,
				queryInfo.getIncludeInferred(), contexts);

		resultHolder.set(new ExceptionConvertingIteration<Statement, QueryEvaluationException>(repoResult) {
			@Override
			protected QueryEvaluationException convert(Exception ex) {
				if (ex instanceof QueryEvaluationException) {
					return (QueryEvaluationException) ex;
				}
				return new QueryEvaluationException(ex);
			}
		});
	});
}
 
Example 16
Source Project: rya   Source File: RdfCloudTripleStoreConnectionTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testDuplicateLiterals() throws Exception {
    RepositoryConnection conn = repository.getConnection();

    IRI loadPerc = VF.createIRI(litdupsNS, "loadPerc");
    Literal lit1 = VF.createLiteral(0.0);
    Literal lit2 = VF.createLiteral(0.0);
    Literal lit3 = VF.createLiteral(0.0);

    conn.add(cpu, loadPerc, lit1);
    conn.add(cpu, loadPerc, lit2);
    conn.add(cpu, loadPerc, lit3);
    conn.commit();

    RepositoryResult<Statement> result = conn.getStatements(cpu, loadPerc, null, true);
    int count = 0;
    while (result.hasNext()) {
        count++;
        result.next();
    }
    result.close();
    assertEquals(1, count);

    //clean up
    conn.remove(cpu, loadPerc, lit1);
    conn.close();
}
 
Example 17
Source Project: rya   Source File: MongoGeoTemporalIndexer.java    License: Apache License 2.0 5 votes vote down vote up
private void updateEvent(final RyaIRI subject, final RyaStatement statement) throws IndexingException, ParseException {
    final EventStorage eventStore = events.get();
    checkState(events != null, "Must set this indexers configuration before storing statements.");

    new EventUpdater(eventStore).update(subject, old -> {
        final Event.Builder updated;
        if(!old.isPresent()) {
            updated = Event.builder()
                .setSubject(subject);
        } else {
            updated = Event.builder(old.get());
        }

        final IRI pred = statement.getObject().getDataType();
        if(pred.equals(GeoConstants.GEO_AS_WKT) || pred.equals(GeoConstants.GEO_AS_GML) ||
           pred.equals(GeoConstants.XMLSCHEMA_OGC_WKT) || pred.equals(GeoConstants.XMLSCHEMA_OGC_GML)) {
            //is geo
            try {
                final Statement geoStatement = RyaToRdfConversions.convertStatement(statement);
                final Geometry geometry = GeoParseUtils.getGeometry(geoStatement, new GmlParser());
                updated.setGeometry(geometry);
            } catch (final ParseException e) {
                LOG.error(e.getMessage(), e);
            }
        } else {
            //is time
            final String dateTime = statement.getObject().getData();
            final Matcher matcher = TemporalInstantRfc3339.PATTERN.matcher(dateTime);
            if (matcher.find()) {
                final TemporalInterval interval = TemporalInstantRfc3339.parseInterval(dateTime);
                updated.setTemporalInterval(interval);
            } else {
                final TemporalInstant instant = new TemporalInstantRfc3339(DateTime.parse(dateTime));
                updated.setTemporalInstant(instant);
            }
        }
        return Optional.of(updated.build());
    });
}
 
Example 18
private RepositoryResult<Statement> getStatementsSingleTriple(Resource subj, IRI pred, Value obj,
		boolean includeInferred, Resource... contexts) throws RepositoryException {
	if (hasStatement(subj, pred, obj, includeInferred, contexts)) {
		Statement st = getValueFactory().createStatement(subj, pred, obj);
		CloseableIteration<Statement, RepositoryException> cursor;
		cursor = new SingletonIteration<>(st);
		return new RepositoryResult<>(cursor);
	} else {
		return new RepositoryResult<>(new EmptyIteration<>());
	}
}
 
Example 19
Source Project: rdf4j   Source File: RDFXMLParser.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void handleReification(Value value) throws RDFParseException, RDFHandlerException {
	PropertyElement predicate = (PropertyElement) peekStack(0);

	if (predicate.isReified()) {
		NodeElement subject = (NodeElement) peekStack(1);
		IRI reifRes = predicate.getReificationURI();
		reifyStatement(reifRes, subject.getResource(), predicate.getURI(), value);
	}
}
 
Example 20
Source Project: rya   Source File: GeoWaveIndexerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDcSearchWithSubject() throws Exception {
    // test a ring around dc
    try (final GeoWaveGeoIndexer f = new GeoWaveGeoIndexer()) {
        f.setConf(conf);
        f.purge(conf);

        final ValueFactory vf = SimpleValueFactory.getInstance();
        final Resource subject = vf.createIRI("foo:subj");
        final IRI predicate = GeoConstants.GEO_AS_WKT;
        final Value object = vf.createLiteral("Point(-77.03524 38.889468)", GeoConstants.XMLSCHEMA_OGC_WKT);
        final Resource context = vf.createIRI("foo:context");

        final Statement statement = vf.createStatement(subject, predicate, object, context);
        f.storeStatement(convertStatement(statement));
        f.flush();

        final double[] IN = { -78, 39, -77, 39, -77, 38, -78, 38, -78, 39 };
        final LinearRing r1 = gf.createLinearRing(new PackedCoordinateSequence.Double(IN, 2));
        final Polygon p1 = gf.createPolygon(r1, new LinearRing[] {});

        // query with correct subject
        Assert.assertEquals(Sets.newHashSet(statement), getSet(f.queryWithin(p1, new StatementConstraints().setSubject(subject))));

        // query with wrong subject
        Assert.assertEquals(Sets.newHashSet(), getSet(f.queryWithin(p1, new StatementConstraints().setSubject(vf.createIRI("foo:subj2")))));
    }
}
 
Example 21
/**
 * Highlights the given field or all fields if null.
 */
@Override
public void highlight(IRI property) {
	query.setHighlight(true);
	String field = (property != null) ? SearchFields.getPropertyField(property) : "*";
	query.addHighlightField(field);
	query.setHighlightSimplePre(SearchFields.HIGHLIGHTER_PRE_TAG);
	query.setHighlightSimplePost(SearchFields.HIGHLIGHTER_POST_TAG);
	query.setHighlightSnippets(2);
}
 
Example 22
Source Project: rdf4j   Source File: FedXDataset.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Set<IRI> getNamedGraphs() {
	if (delegate == null) {
		return Collections.emptySet();
	}
	return delegate.getNamedGraphs();
}
 
Example 23
@Override
public RepositoryResult<Statement> getStatements(Resource subj, IRI pred, Value obj, boolean includeInferred,
		Resource... contexts) throws RepositoryException {
	try {
		StatementCollector collector = new StatementCollector();
		exportStatements(subj, pred, obj, includeInferred, collector, contexts);
		return createRepositoryResult(collector.getStatements());
	} catch (RDFHandlerException e) {
		// found a bug in StatementCollector?
		throw new RuntimeException(e);
	}
}
 
Example 24
Source Project: rya   Source File: InferenceEngineTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testPropertyTypes() throws Exception {
    final String ontology = "INSERT DATA { GRAPH <http://updated/test> {\n"
            + "  <urn:comment> a owl:AnnotationProperty .\n"
            + "  <urn:olderThan> a owl:TransitiveProperty, owl:IrreflexiveProperty, owl:AsymmetricProperty .\n"
            + "  <urn:notYoungerThan> a owl:TransitiveProperty, owl:ReflexiveProperty .\n"
            + "  <urn:related> a owl:Property, owl:SymmetricProperty, owl:TransitiveProperty .\n"
            + "  <urn:knows> a owl:SymmetricProperty, owl:ObjectProperty, owl:ReflexiveProperty .\n"
            + "  <urn:sameAgeAs> a owl:SymmetricProperty, owl:ReflexiveProperty, owl:TransitiveProperty .\n"
            + "}}";
    conn.prepareUpdate(QueryLanguage.SPARQL, ontology).execute();
    inferenceEngine.refreshGraph();
    final IRI comment = VF.createIRI("urn:comment"); // none of the three supported types
    final IRI older = VF.createIRI("urn:olderThan"); // transitive only
    final IRI notYounger = VF.createIRI("urn:notYoungerThan"); // transitive and reflexive
    final IRI related = VF.createIRI("urn:related"); // transitive and symmetric
    final IRI knows = VF.createIRI("urn:knows"); // reflexive and symmetric
    final IRI sameAge = VF.createIRI("urn:sameAgeAs"); // all three
    // symmetry
    Assert.assertFalse(inferenceEngine.isSymmetricProperty(comment));
    Assert.assertFalse(inferenceEngine.isSymmetricProperty(older));
    Assert.assertFalse(inferenceEngine.isSymmetricProperty(notYounger));
    Assert.assertTrue(inferenceEngine.isSymmetricProperty(related));
    Assert.assertTrue(inferenceEngine.isSymmetricProperty(knows));
    Assert.assertTrue(inferenceEngine.isSymmetricProperty(sameAge));
    // transitivity
    Assert.assertFalse(inferenceEngine.isTransitiveProperty(comment));
    Assert.assertTrue(inferenceEngine.isTransitiveProperty(older));
    Assert.assertTrue(inferenceEngine.isTransitiveProperty(notYounger));
    Assert.assertTrue(inferenceEngine.isTransitiveProperty(related));
    Assert.assertFalse(inferenceEngine.isTransitiveProperty(knows));
    Assert.assertTrue(inferenceEngine.isTransitiveProperty(sameAge));
    // reflexivity
    Assert.assertFalse(inferenceEngine.isReflexiveProperty(comment));
    Assert.assertFalse(inferenceEngine.isReflexiveProperty(older));
    Assert.assertTrue(inferenceEngine.isReflexiveProperty(notYounger));
    Assert.assertFalse(inferenceEngine.isReflexiveProperty(related));
    Assert.assertTrue(inferenceEngine.isReflexiveProperty(knows));
    Assert.assertTrue(inferenceEngine.isReflexiveProperty(sameAge));
}
 
Example 25
Source Project: rdf4j   Source File: RDFJSONWriter.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Returns the correct syntax for a Resource, depending on whether it is a URI or a Blank Node (ie, BNode)
 *
 * @param uriOrBnode The resource to serialise to a string
 * @return The string value of the sesame resource
 */
public static String resourceToString(final Resource uriOrBnode) {
	if (uriOrBnode instanceof IRI) {
		return uriOrBnode.stringValue();
	} else {
		return "_:" + ((BNode) uriOrBnode).getID();
	}
}
 
Example 26
@Override
public boolean hasStatements(Resource subj,
		IRI pred, Value obj, QueryInfo queryInfo, Resource... contexts) throws RepositoryException {
	try (RepositoryConnection conn = endpoint.getConnection()) {
		return conn.hasStatement(subj, pred, obj, queryInfo.getIncludeInferred(), contexts);
	}
}
 
Example 27
Source Project: semagrow   Source File: VOIDStatistics.java    License: Apache License 2.0 5 votes vote down vote up
private long getDistinctObjects(StatementPattern pattern, IRI source) {
    Value pVal = pattern.getPredicateVar().getValue();
    Value sVal = pattern.getSubjectVar().getValue();
    Value oVal = pattern.getObjectVar().getValue();

    Set<Resource> datasets  = getMatchingDatasetsOfEndpoint(source);

    if (datasets.isEmpty())
        return 0;

    if (oVal != null)
        return 1;

    Set<Resource> pDatasets = new HashSet<Resource>(datasets);
    Set<Resource> sDatasets = new HashSet<Resource>(datasets);

    if (pVal != null)
        pDatasets.retainAll(getMatchingDatasetsOfPredicate((IRI) pVal));

    if (sVal != null && sVal instanceof IRI)
        sDatasets.retainAll(getMatchingDatasetsOfSubject((IRI)sVal));

    Set<Resource> spDatasets = new HashSet<Resource>(pDatasets);
    spDatasets.retainAll(sDatasets);

    if (!spDatasets.isEmpty()) { // datasets that match both the predicate and subject
        return getDistinctObjects(spDatasets);
    } else if (pVal != null && !pDatasets.isEmpty()) {
        return getDistinctObjects(pDatasets);
    } else if (sVal != null && !sDatasets.isEmpty()) {
        return getDistinctObjects(sDatasets);
    }
    else {
        return getDistinctObjects(datasets);
    }
}
 
Example 28
private void writeLiteral(Literal literal) throws IOException {
	String label = literal.getLabel();
	IRI datatype = literal.getDatatype();

	int marker = PLAIN_LITERAL_RECORD_MARKER;

	if (Literals.isLanguageLiteral(literal)) {
		marker = LANG_LITERAL_RECORD_MARKER;
	} else {
		String namespace = datatype.getNamespace();

		if (!namespaceTable.containsKey(namespace)) {
			// Assign an ID to this new namespace
			writeNamespace(namespace);
		}

		marker = DATATYPE_LITERAL_RECORD_MARKER;
	}

	out.writeByte(marker);
	writeString(label);

	if (Literals.isLanguageLiteral(literal)) {
		writeString(literal.getLanguage().get());
	} else {
		writeQName(datatype);
	}
}
 
Example 29
Source Project: rya   Source File: StatementSerializer.java    License: Apache License 2.0 5 votes vote down vote up
private static Literal parseLiteral(final String fullLiteralString) {
    Validate.notNull(fullLiteralString);
    Validate.isTrue(fullLiteralString.length() > 1);

    if (fullLiteralString.endsWith("\"")) {
        final String fullLiteralWithoutQuotes = fullLiteralString.substring(1, fullLiteralString.length() - 1);
        return VF.createLiteral(fullLiteralWithoutQuotes);
    } else {

        // find the closing quote
        final int labelEnd = fullLiteralString.lastIndexOf("\"");

        final String label = fullLiteralString.substring(1, labelEnd);

        final String data = fullLiteralString.substring(labelEnd + 1);

        if (data.startsWith(LiteralLanguageUtils.LANGUAGE_DELIMITER)) {
            // the data is "language"
            final String lang = data.substring(1);
            return VF.createLiteral(label, lang);
        } else if (data.startsWith("^^<")) {
            // the data is a "datatype"
            final String datatype = data.substring(3, data.length() - 1);
            final IRI datatypeUri = VF.createIRI(datatype);
            return VF.createLiteral(label, datatypeUri);
        }
    }
    return null;

}
 
Example 30
Source Project: rdf4j   Source File: SpinSailTest.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Ignore("This test shows how the SpinSail fails on transactional workloads.")
@Test
public void testDeepConstructRule() throws Exception {
	loadStatements("testDeepConstructRule.ttl");

	ValueFactory vf = SimpleValueFactory.getInstance();

	String ns = "http://example.org/";

	IRI ex1 = vf.createIRI(ns, "ex1");
	IRI TestClass = vf.createIRI(ns, "TestClass");
	IRI prop = vf.createIRI(ns, "prop");
	IRI ex2 = vf.createIRI(ns, "ex2");
	IRI ex3 = vf.createIRI(ns, "ex3");
	IRI ex4 = vf.createIRI(ns, "ex4");

	conn.begin();
	conn.add(ex1, RDF.TYPE, TestClass);
	conn.add(ex1, prop, ex2);

	// comment out these two lines, so that all statements are added in the same transaction. This will make the
	// test pass.
	conn.commit();
	conn.begin();

	conn.add(ex2, FOAF.KNOWS, ex3);
	conn.add(ex3, FOAF.KNOWS, ex4);
	conn.commit();

	assertStatements("testDeepConstructRule-expected.ttl");

}