org.eclipse.rdf4j.model.vocabulary.RDF Java Examples

The following examples show how to use org.eclipse.rdf4j.model.vocabulary.RDF. 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: SnapshotTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void test_mergeOptionalInsert() throws Exception {
	a.add(PICASSO, RDF.TYPE, PAINTER);
	b.add(REMBRANDT, RDF.TYPE, PAINTER);
	b.add(REMBRANDT, PAINTS, NIGHTWATCH);
	b.add(REMBRANDT, PAINTS, ARTEMISIA);
	b.add(REMBRANDT, PAINTS, DANAE);
	a.begin(level);
	b.begin(level);
	// PICASSO *is* a known PAINTER
	a.add(PICASSO, PAINTS, GUERNICA);
	a.add(PICASSO, PAINTS, JACQUELINE);
	b.prepareUpdate(QueryLanguage.SPARQL, "INSERT { ?painting a <Painting> }\n" + "WHERE { ?painter a <Painter> "
			+ "OPTIONAL { ?painter <paints> ?painting } }", NS).execute();
	a.commit();
	assertEquals(3, size(b, REMBRANDT, PAINTS, null, false));
	b.commit();
	assertEquals(10, size(a, null, null, null, false));
}
 
Example #2
Source File: KnowledgeBaseExporterTest.java    From inception with Apache License 2.0 6 votes vote down vote up
private KnowledgeBase buildKnowledgeBase(String name) throws Exception
{
    KnowledgeBase kb = new KnowledgeBase();
    kb.setRepositoryId("id-" + name);
    kb.setName(name);
    kb.setProject(sourceProject);
    kb.setSubclassIri(RDFS.SUBCLASSOF);
    kb.setTypeIri(RDF.TYPE);
    kb.setDescriptionIri(RDFS.COMMENT);
    kb.setLabelIri(RDFS.LABEL);
    kb.setPropertyTypeIri(RDF.PROPERTY);
    kb.setPropertyLabelIri(RDFS.LABEL);
    kb.setPropertyDescriptionIri(RDFS.COMMENT);
    kb.setSubPropertyIri(RDFS.SUBPROPERTYOF);
    kb.setMaxResults(1000);
    ValueFactory vf = SimpleValueFactory.getInstance();
    kb.setRootConcepts(Arrays
        .asList(vf.createIRI("http://www.ics.forth.gr/isl/CRMinf/I1_Argumentation"),
            vf.createIRI("http://www.ics.forth.gr/isl/CRMinf/I1_Argumentation")));
    kb.setDefaultLanguage("en");
    return kb;
}
 
Example #3
Source File: SparqlToPipelineTransformVisitorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testProjection() throws Exception {
    StatementPattern isUndergrad = new StatementPattern(new Var("x"), constant(RDF.TYPE), constant(UNDERGRAD));
    StatementPattern isCourse = new StatementPattern(new Var("course"), constant(RDF.TYPE), constant(COURSE));
    StatementPattern hasEdge = new StatementPattern(new Var("x"), new Var("p"), new Var("course"));
    ProjectionElemList projectionElements = new ProjectionElemList(
            new ProjectionElem("p", "relation"),
            new ProjectionElem("course"));
    QueryRoot queryTree = new QueryRoot(new Projection(
            new Join(new Join(isCourse, hasEdge), isUndergrad),
            projectionElements));
    SparqlToPipelineTransformVisitor visitor = new SparqlToPipelineTransformVisitor(collection);
    queryTree.visit(visitor);
    Assert.assertTrue(queryTree.getArg() instanceof AggregationPipelineQueryNode);
    AggregationPipelineQueryNode pipelineNode = (AggregationPipelineQueryNode) queryTree.getArg();
    Assert.assertEquals(Sets.newHashSet("relation", "course"), pipelineNode.getAssuredBindingNames());
}
 
Example #4
Source File: AntecedentVisitorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testConstructQuery() throws Exception {
    String text = "PREFIX foaf: <" + FOAF.NAMESPACE + ">\n"
            + "CONSTRUCT {\n"
            + "  ?y foaf:knows ?x .\n"
            + "  ?y <urn:knows> ?x .\n"
            + "  ?x <urn:knows> ?y .\n"
            + "} WHERE {\n"
            + "  ?x a foaf:Person .\n"
            + "  ?y a foaf:Person .\n"
            + "  ?x foaf:knows ?y .\n"
            + "}";
    ParsedQuery query = new SPARQLParser().parseQuery(text, null);
    AntecedentVisitor visitor = new AntecedentVisitor();
    query.getTupleExpr().visit(visitor);
    Set<StatementPattern> expected = Sets.newHashSet(
            new StatementPattern(new Var("x"), c(RDF.TYPE), c(FOAF.PERSON)),
            new StatementPattern(new Var("y"), c(RDF.TYPE), c(FOAF.PERSON)),
            new StatementPattern(new Var("x"), c(FOAF.KNOWS), new Var("y")));
    Assert.assertEquals(expected, visitor.getAntecedents());
}
 
Example #5
Source File: RDFXMLPrettyWriterTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void sequenceItemsAreAbbreviated() throws RDFHandlerException, IOException {
	StringWriter writer = new StringWriter();
	RDFWriter rdfWriter = rdfWriterFactory.getWriter(writer);

	rdfWriter.startRDF();

	Resource res = vf.createIRI("http://example.com/#");

	rdfWriter.handleStatement(vf.createStatement(res, RDF.TYPE, RDF.BAG));

	rdfWriter.handleStatement(
			vf.createStatement(res, vf.createIRI(RDF.NAMESPACE + "_1"), vf.createIRI("http://example.com/#1")));
	rdfWriter.handleStatement(
			vf.createStatement(res, vf.createIRI(RDF.NAMESPACE + "_2"), vf.createIRI("http://example.com/#2")));
	rdfWriter.endRDF();

	List<String> rdfLines = rdfOpenTags(writer.toString());

	assertEquals(Arrays.asList("<rdf:RDF", "<rdf:Bag", "<rdf:li", "<rdf:li"), rdfLines);
}
 
Example #6
Source File: LocalReasonerTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testAllValuesFromReverse() throws Exception {
    schema.processTriple(TestUtils.statement(TestUtils.uri("x"),
        OWL.ALLVALUESFROM, TestUtils.uri("Human")));
    schema.processTriple(TestUtils.statement(TestUtils.uri("x"),
        OWL.ONPROPERTY, TestUtils.uri("hasParent")));
    reasoner.processFact(TestUtils.fact(TestUtils.NODE, RDF.TYPE,
        TestUtils.uri("x")));
    reasoner.processFact(TestUtils.fact(TestUtils.NODE,
        TestUtils.uri("hasParent"), TestUtils.uri("v")));
    reasoner.getTypes();
    for (Fact t : reasoner.getFacts()) {
        if (t.getSubject().equals(TestUtils.uri("v"))
            && t.getPredicate().equals(RDF.TYPE)
            && t.getObject().equals(TestUtils.uri("Human"))) {
            return;
        }
    }
    Assert.fail("If x is a property restriction [owl:allValuesFrom c]"
        + " on property p; (u type x) then (u p v) should imply (v type c).");
}
 
Example #7
Source File: AbstractParserHandlingTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public final void testSkolemization() throws Exception {
	Model expectedModel = new LinkedHashModel();
	BNode subj = vf.createBNode();
	expectedModel
			.add(vf.createStatement(subj, RDF.VALUE, vf.createLiteral(KNOWN_DATATYPE_VALUE, KNOWN_DATATYPE_URI)));
	expectedModel
			.add(vf.createStatement(subj, RDF.VALUE, vf.createLiteral(KNOWN_LANGUAGE_VALUE, KNOWN_LANGUAGE_TAG)));
	InputStream input = getKnownDatatypeStream(expectedModel);

	testParser.getParserConfig().set(BasicParserSettings.SKOLEMIZE_ORIGIN, "http://example.com");

	testParser.parse(input, BASE_URI);

	assertErrorListener(0, 0, 0);
	assertModel(expectedModel); // isomorphic
	assertNotEquals(new HashSet<>(expectedModel), new HashSet<>(testStatements)); // blank nodes not preserved
	assertTrue(Models.subjectBNodes(testStatements).isEmpty()); // skolemized
}
 
Example #8
Source File: RDFQueryLogParser.java    From semagrow with Apache License 2.0 6 votes vote down vote up
@Override
public void parseQueryLog(InputStream in) throws IOException, QueryLogException {
    if (handler == null)
        throw new QueryLogException("No query log handler defined");

    try {
        model = Rio.parse(in, "", RDFFormat.NTRIPLES);
    } catch (Exception e) {
        throw new QueryLogException(e);
    }

    Model queryRecords = model.filter(null, RDF.TYPE, QFR.QUERYRECORD);

    for (Resource qr : queryRecords.subjects()) {
        QueryLogRecord record = parseQueryRecord(qr,model);
        handler.handleQueryRecord(record);
    }
}
 
Example #9
Source File: DAWGTestResultSetParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void endRDF() throws RDFHandlerException {
	try {
		Resource resultSetNode = Models.subject(graph.filter(null, RDF.TYPE, RESULTSET))
				.orElseThrow(() -> new RDFHandlerException("no instance of type ResultSet"));

		List<String> bindingNames = getBindingNames(resultSetNode);
		tqrHandler.startQueryResult(bindingNames);

		for (Value solutionNode : Models.getProperties(graph, resultSetNode, SOLUTION)) {
			if (solutionNode instanceof Resource) {
				reportSolution((Resource) solutionNode, bindingNames);
			} else {
				throw new RDFHandlerException("Value for " + SOLUTION + " is not a resource: " + solutionNode);
			}
		}

		tqrHandler.endQueryResult();
	} catch (TupleQueryResultHandlerException e) {
		throw new RDFHandlerException(e.getMessage(), e);
	}
}
 
Example #10
Source File: HalyardValueExprEvaluation.java    From Halyard with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluate a {@link Datatype} node
 * @param node the node to evaluate
 * @param bindings the set of named value bindings
 * @return a {@link Literal} representing the evaluation of the argument of the {@link Datatype}.
 * @throws ValueExprEvaluationException
 * @throws QueryEvaluationException
 */
private Value evaluate(Datatype node, BindingSet bindings) throws ValueExprEvaluationException, QueryEvaluationException {
    Value v = evaluate(node.getArg(), bindings);
    if (v instanceof Literal) {
        Literal literal = (Literal) v;
        if (literal.getDatatype() != null) {
            // literal with datatype
            return literal.getDatatype();
        } else if (literal.getLanguage() != null) {
            return RDF.LANGSTRING;
        } else {
            // simple literal
            return XMLSchema.STRING;
        }
    }
    throw new ValueExprEvaluationException();
}
 
Example #11
Source File: RDFXMLParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Checks whether the property element name is from the RDF namespace and, if so, if it is allowed to be used in a
 * property element. If the name is equal to one of the disallowed names (RDF, ID, about, parseType, resource and
 * li), an error is generated. If the name is not defined in the RDF namespace, but it claims that it is from this
 * namespace, a warning is generated.
 *
 * @param setting
 */
private void checkPropertyEltName(String namespaceURI, String localName, String qName, RioSetting<Boolean> setting)
		throws RDFParseException {
	if (RDF.NAMESPACE.equals(namespaceURI)) {

		if (localName.equals("li") || localName.equals("Seq") || localName.equals("Bag") || localName.equals("Alt")
				|| localName.equals("Statement") || localName.equals("Property") || localName.equals("List")
				|| localName.equals("subject") || localName.equals("predicate") || localName.equals("object")
				|| localName.equals("type") || localName.equals("value") || localName.equals("first")
				|| localName.equals("rest") || localName.equals("nil") || localName.startsWith("_")) {
			// These are OK
		} else if (localName.equals("Description") || localName.equals("RDF") || localName.equals("ID")
				|| localName.equals("about") || localName.equals("parseType") || localName.equals("resource")
				|| localName.equals("nodeID") || localName.equals("datatype")) {
			reportError("<" + qName + "> not allowed as property element", setting);
		} else if (localName.equals("bagID") || localName.equals("aboutEach")
				|| localName.equals("aboutEachPrefix")) {
			reportError(qName + " is no longer a valid RDF name", setting);
		} else {
			reportWarning("unknown rdf element <" + qName + ">");
		}
	}
}
 
Example #12
Source File: ElasticsearchStoreTransactionsTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testGetDataSailRepository() {
	SailRepository elasticsearchStore = new SailRepository(this.elasticsearchStore);
	try (SailRepositoryConnection connection = elasticsearchStore.getConnection()) {
		connection.add(RDF.TYPE, RDF.TYPE, RDFS.RESOURCE);

		List<? extends Statement> statements = Iterations.asList(connection.getStatements(null, null, null, true));

		System.out.println(Arrays.toString(statements.toArray()));

		assertEquals(1, statements.size());
		assertEquals(SimpleValueFactory.getInstance().createStatement(RDF.TYPE, RDF.TYPE, RDFS.RESOURCE),
				statements.get(0));
	}

}
 
Example #13
Source File: VisulizerTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test(expected = SailException.class)
public void minCount() throws Exception {

	ShaclSail shaclSail = Utils.getInitializedShaclSail("shacl.ttl");

	try (NotifyingSailConnection connection = shaclSail.getConnection()) {
		SimpleValueFactory vf = SimpleValueFactory.getInstance();
		connection.begin();
		BNode bNode = vf.createBNode();
		connection.addStatement(bNode, RDF.TYPE, RDFS.RESOURCE);
		connection.addStatement(bNode, RDFS.LABEL, vf.createLiteral(""));
		connection.commit();

		shaclSail.setLogValidationPlans(true);

		connection.begin();
		BNode bNode2 = vf.createBNode();
		connection.addStatement(bNode2, RDF.TYPE, RDFS.RESOURCE);
		connection.removeStatement(null, bNode, RDFS.LABEL, vf.createLiteral(""));

		connection.commit();
	}

}
 
Example #14
Source File: ConfigViewTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testRender() throws Exception {

	ConfigView configView = ConfigView.getInstance();

	Model configData = new LinkedHashModelFactory().createEmptyModel();
	configData.add(RDF.ALT, RDF.TYPE, RDFS.CLASS);

	Map<Object, Object> map = new LinkedHashMap<>();
	map.put(ConfigView.HEADERS_ONLY, false);
	map.put(ConfigView.CONFIG_DATA_KEY, configData);
	map.put(ConfigView.FORMAT_KEY, RDFFormat.NTRIPLES);

	final MockHttpServletRequest request = new MockHttpServletRequest();
	request.setMethod(HttpMethod.GET.name());
	request.addHeader("Accept", RDFFormat.NTRIPLES.getDefaultMIMEType());

	MockHttpServletResponse response = new MockHttpServletResponse();

	configView.render(map, request, response);

	String ntriplesData = response.getContentAsString();
	Model renderedData = Rio.parse(new StringReader(ntriplesData), "", RDFFormat.NTRIPLES);
	assertThat(renderedData).isNotEmpty();
}
 
Example #15
Source File: HalyardSummary.java    From Halyard with Apache License 2.0 6 votes vote down vote up
@Override
protected void setup(Context context) throws IOException, InterruptedException {
    this.conf = context.getConfiguration();
    this.splitOutput = conf.get(TARGET).contains("{0}");
    this.outputLimit = conf.getLong("mapreduce.input.fileinputformat.split.maxsize", Long.MAX_VALUE);
    String ng = conf.get(TARGET_GRAPH);
    this.namedGraph = ng == null ? null : SVF.createIRI(ng);
    this.decimationFactor = conf.getInt(DECIMATION_FACTOR, DEFAULT_DECIMATION_FACTOR);
    sail = new HBaseSail(conf, conf.get(SOURCE), false, 0, true, 0, null, null);
    sail.initialize();
    setupOutput();
    write(CARDINALITY, RDF.TYPE, RDF.PROPERTY);
    write(CARDINALITY, RDFS.LABEL, SVF.createLiteral("cardinality"));
    write(CARDINALITY, RDFS.COMMENT, SVF.createLiteral("cardinality is positive integer [0..63], it is a binary logarithm of the pattern occurences (2^63 is the maximum allowed number of occurences)"));
    write(CARDINALITY, RDFS.RANGE, XMLSchema.INTEGER);
}
 
Example #16
Source File: ClassBenchmarkEmpty.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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);
		IRI friend = vf.createIRI("http://example.com/friend" + i + "_" + j);

		statements.add(vf.createStatement(iri, RDF.TYPE, FOAF.PERSON));
		statements.add(vf.createStatement(iri, FOAF.KNOWS, friend));
		statements.add(vf.createStatement(friend, RDF.TYPE, FOAF.PERSON));
	}));

	System.gc();

}
 
Example #17
Source File: RemoteRepositoryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #18
Source File: TurtleWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void writePredicate(IRI predicate) throws IOException {
	if (predicate.equals(RDF.TYPE)) {
		// Write short-cut for rdf:type
		writer.write("a");
	} else {
		writeURI(predicate);
	}
}
 
Example #19
Source File: SpinRenderer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void meet(Regex node) throws RDFHandlerException {
	Resource currentSubj = subject;
	flushPendingStatement();
	handler.handleStatement(valueFactory.createStatement(subject, RDF.TYPE, SP.REGEX));
	predicate = SP.ARG1_PROPERTY;
	node.getLeftArg().visit(this);
	predicate = SP.ARG2_PROPERTY;
	node.getRightArg().visit(this);
	subject = currentSubj;
	predicate = null;
}
 
Example #20
Source File: RdfsShaclConnectionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void fill(ShaclSail shaclSail) {
	try (NotifyingSailConnection connection = shaclSail.getConnection()) {
		connection.begin();
		connection.addStatement(subSub, RDFS.SUBCLASSOF, sub);
		connection.addStatement(sub, RDFS.SUBCLASSOF, sup);
		connection.addStatement(aSubSub, RDF.TYPE, subSub);
		connection.addStatement(aSub, RDF.TYPE, sub);
		connection.addStatement(aSup, RDF.TYPE, sup);
		connection.commit();
	}
}
 
Example #21
Source File: IsolationLevelTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Every connection must support reading it own changes
 */
private void readPending(IsolationLevel level) throws RepositoryException {
	clear(store);
	try (RepositoryConnection con = store.getConnection();) {
		con.begin(level);
		con.add(RDF.NIL, RDF.TYPE, RDF.LIST);
		assertEquals(1, count(con, RDF.NIL, RDF.TYPE, RDF.LIST, false));
		con.remove(RDF.NIL, RDF.TYPE, RDF.LIST);
		con.commit();
	}
}
 
Example #22
Source File: RDFXMLParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Retrieves the object resource of a property element using relevant attributes (rdf:resource and rdf:nodeID) from
 * its attributes list.
 *
 * @return a resource or a bNode.
 */
private Resource getPropertyResource(Atts atts) throws RDFParseException {
	Att resource = atts.removeAtt(RDF.NAMESPACE, "resource");
	Att nodeID = atts.removeAtt(RDF.NAMESPACE, "nodeID");

	if (getParserConfig().get(XMLParserSettings.FAIL_ON_NON_STANDARD_ATTRIBUTES)) {
		int definedAttsCount = 0;

		if (resource != null) {
			definedAttsCount++;
		}
		if (nodeID != null) {
			definedAttsCount++;
		}

		if (definedAttsCount > 1) {
			reportError("Only one of the attributes rdf:resource or rdf:nodeID can be used here",
					XMLParserSettings.FAIL_ON_NON_STANDARD_ATTRIBUTES);
		}
	}

	Resource result = null;

	if (resource != null) {
		result = resolveURI(resource.getValue());
	} else if (nodeID != null) {
		result = createNode(nodeID.getValue());
	} else {
		// No resource specified, generate a bNode
		result = createNode();
	}

	return result;
}
 
Example #23
Source File: SpinRenderer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void meet(MathExpr node) throws RDFHandlerException {
	Resource currentSubj = subject;
	flushPendingStatement();
	handler.handleStatement(valueFactory.createStatement(subject, RDF.TYPE, toValue(node.getOperator())));
	predicate = SP.ARG1_PROPERTY;
	node.getLeftArg().visit(this);
	predicate = SP.ARG2_PROPERTY;
	node.getRightArg().visit(this);
	subject = currentSubj;
	predicate = null;
}
 
Example #24
Source File: RDFCollectionsTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testExtract() {
	Resource head = vf.createBNode();
	Model m = RDFCollections.asRDF(values, head, new TreeModel());

	// add something to the model that is not part of the RDF collection.
	m.add(RDF.TYPE, RDF.TYPE, RDF.PROPERTY);

	Model collection = RDFCollections.getCollection(m, head, new TreeModel());
	assertNotNull(collection);
	assertFalse(collection.contains(RDF.TYPE, RDF.TYPE, RDF.PROPERTY));
	assertTrue(collection.contains(null, RDF.FIRST, a));
	assertTrue(collection.contains(null, RDF.FIRST, b));
	assertTrue(collection.contains(null, RDF.FIRST, c));
}
 
Example #25
Source File: RepositoryConnectionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testQueryInTransaction() throws Exception {
	testCon.add(bob, RDF.TYPE, FOAF.PERSON);

	testCon.begin();
	String query = "SELECT * where {?x a ?y }";
	try (TupleQueryResult result = testCon.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate();) {
		// test verifies that query as part of transaction executes and returns
		// a result
		assertNotNull(result);
		assertTrue(result.hasNext());
		testCon.commit();
	}
}
 
Example #26
Source File: RyaToRdfConversions.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a {@link RyaType} into a {@link Literal} representation of the
 * {@code ryaType}.
 * @param ryaType the {@link RyaType} to convert.
 * @return the {@link Literal} representation of the {@code ryaType}.
 */
public static Literal convertLiteral(final RyaType ryaType) {
    if (XMLSchema.STRING.equals(ryaType.getDataType())) {
        return VF.createLiteral(ryaType.getData());
    } else if (RDF.LANGSTRING.equals(ryaType.getDataType())) {
        final String data = ryaType.getData();
        final String language = ryaType.getLanguage();
        if (language != null && Literals.isValidLanguageTag(language)) {
            return VF.createLiteral(data, language);
        } else {
            return VF.createLiteral(data, LiteralLanguageUtils.UNDETERMINED_LANGUAGE);
        }
    }
    return VF.createLiteral(ryaType.getData(), ryaType.getDataType());
}
 
Example #27
Source File: MemTripleSourceTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test method for
 * {@link org.eclipse.rdf4j.sail.memory.MemTripleSource#getStatements(org.eclipse.rdf4j.model.Resource, org.eclipse.rdf4j.model.IRI, org.eclipse.rdf4j.model.Value, org.eclipse.rdf4j.model.Resource[])}
 * .
 */
@Test
public final void testGetStatementsOneContextPredicateOwlClassNoContexts() throws Exception {
	loadTestData("/alp-testdata.ttl", this.alice);
	TripleSource source = getTripleSourceCommitted();

	try (CloseableIteration<? extends Statement, QueryEvaluationException> statements = source.getStatements(null,
			RDF.TYPE, OWL.CLASS)) {
		List<Statement> list = Iterations.asList(statements);

		assertEquals(4, list.size());
	}
}
 
Example #28
Source File: SnapshotTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void test_afterInsertDataPattern() throws Exception {
	a.begin(level);
	b.begin(level);
	a.prepareUpdate(QueryLanguage.SPARQL, "INSERT DATA { <picasso> a <Painter> }", NS).execute();
	b.prepareUpdate(QueryLanguage.SPARQL, "INSERT DATA { <rembrandt> a <Painter> }", NS).execute();
	assertEquals(1, size(a, null, RDF.TYPE, PAINTER, false));
	a.commit();
	b.commit();
	assertEquals(2, size(b, null, RDF.TYPE, PAINTER, false));
}
 
Example #29
Source File: RDFStoreTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testDuplicateGetStatementAfterCommit() {
	con.begin();

	con.addStatement(RDF.SUBJECT, RDF.PREDICATE, RDF.OBJECT);
	con.commit();
	con.begin();
	con.addStatement(RDF.SUBJECT, RDF.PREDICATE, RDF.OBJECT);
	con.commit();
	try (Stream<? extends Statement> stream = con.getStatements(null, null, null, false).stream()) {
		long count = stream.count();
		Assert.assertEquals("Statement should appear once", 1, count);

	}
}
 
Example #30
Source File: QueryBenchmark.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Benchmark
public boolean removeByQuery() {

	try (SailRepositoryConnection connection = repository.getConnection()) {
		connection.begin(IsolationLevels.NONE);
		connection.remove((Resource) null, RDF.TYPE, null);
		connection.commit();
		connection.begin(IsolationLevels.NONE);
		connection.add(statementList);
		connection.commit();
	}
	return hasStatement();

}