Java Code Examples for org.eclipse.rdf4j.model.Model#size()

The following examples show how to use org.eclipse.rdf4j.model.Model#size() . 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: ArrangedWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private synchronized Set<Statement> queueBlankStatements(SubjectInContext key) {
	Model firstMatch = blanks.filter(key.getSubject(), null, null, key.getContext());
	Model matches = firstMatch.isEmpty() ? blankReferences.filter(key.getSubject(), null, null, key.getContext())
			: firstMatch;
	if (matches.isEmpty()) {
		return null;
	}
	Set<Statement> set = stmtBySubject.get(key);
	if (set == null) {
		stmtBySubject.put(key, set = new TreeSet<>(comparator));
	}
	set.addAll(matches);
	if (firstMatch.isEmpty()) {
		// repeat blank node values
		queueSize += matches.size();
	} else {
		if (repeatBlankNodes && key.getSubject() instanceof BNode && isStillReferenced(key)) {
			blankReferences.addAll(matches);
		}
		blanks.remove(key.getSubject(), null, null, key.getContext());
	}
	return set;
}
 
Example 2
Source File: SourceGenerator.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Identify all of the subjects in the ontology that have the rdf:type of
 * owl:Class.
 *
 * @return The {@link Collection} of {@link IRI}s that are classes in the
 * ontology
 */
private Collection<IRI> identifyClasses() {
    final Model owlClasses = this.model.filter(null, RDF.TYPE, OWL.CLASS);
    final Model rdfsClasses = this.model.filter(null, RDF.TYPE, RDFS.CLASS);
    classIris = new HashSet<>(owlClasses.size() + rdfsClasses.size());

    owlClasses.stream()
            .map(org.eclipse.rdf4j.model.Statement::getSubject)
            .filter(subject -> subject instanceof IRI)
            .map(subject -> (IRI) subject)
            .forEach(classIris::add);

    rdfsClasses.stream()
            .map(org.eclipse.rdf4j.model.Statement::getSubject)
            .filter(subject -> subject instanceof IRI)
            .map(subject -> (IRI) subject)
            .forEach(classIris::add);
    return classIris;
}
 
Example 3
Source File: SHACLManifestTestSuiteFactory.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private IRI readTurtle(Model manifests, URL url, String baseURI, String... excludedSubdirs)
		throws IOException, RDFParseException {
	if (baseURI == null) {
		baseURI = url.toExternalForm();
	}
	ParsedIRI baseIRI = ParsedIRI.create(baseURI);
	SimpleValueFactory vf = SimpleValueFactory.getInstance();
	IRI manifest = vf.createIRI(baseIRI.toString());
	int before = manifests.size();

	try (InputStream in = url.openStream()) {
		RDFParser rdfParser = new TurtleParser();

		ContextStatementCollector collection = new ContextStatementCollector(manifests, vf, manifest);
		rdfParser.setRDFHandler(collection);

		rdfParser.parse(in, baseIRI.toString());
		for (Map.Entry<String, String> e : collection.getNamespaces().entrySet()) {
			manifests.setNamespace(e.getKey(), e.getValue());
		}
	}
	if (before < manifests.size()) {
		for (Value included : new LinkedHashSet<>(
				manifests.filter(manifest, vf.createIRI(MF_INCLUDE), null).objects())) {
			String subManifestFile = included.stringValue();
			if (includeSubManifest(subManifestFile, excludedSubdirs)) {
				readTurtle(manifests, new URL(subManifestFile), subManifestFile, excludedSubdirs);
			}
		}
	}
	return manifest;
}
 
Example 4
Source File: RepositoryConfigUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static Statement getIDStatement(Model model, String repositoryID) {
	Literal idLiteral = SimpleValueFactory.getInstance().createLiteral(repositoryID);
	Model idStatementList = model.filter(null, REPOSITORYID, idLiteral);

	if (idStatementList.size() == 1) {
		return idStatementList.iterator().next();
	} else if (idStatementList.isEmpty()) {
		return null;
	} else {
		throw new RepositoryConfigException("Multiple ID-statements for repository ID " + repositoryID);
	}
}
 
Example 5
Source File: Models.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Compares two RDF models, and returns <tt>true</tt> if they consist of isomorphic graphs and the isomorphic graph
 * identifiers map 1:1 to each other. RDF graphs are isomorphic graphs if statements from one graphs can be mapped
 * 1:1 on to statements in the other graphs. In this mapping, blank nodes are not considered mapped when having an
 * identical internal id, but are mapped from one graph to the other by looking at the statements in which the blank
 * nodes occur. A Model can consist of more than one graph (denoted by context identifiers). Two models are
 * considered isomorphic if for each of the graphs in one model, an isomorphic graph exists in the other model, and
 * the context identifiers of these graphs are either identical or (in the case of blank nodes) map 1:1 on each
 * other.
 *
 * @see <a href="http://www.w3.org/TR/rdf11-concepts/#graph-isomorphism">RDF Concepts &amp; Abstract Syntax, section
 *      3.6 (Graph Comparison)</a>
 */
public static boolean isomorphic(Iterable<? extends Statement> model1, Iterable<? extends Statement> model2) {
	if (model1 == model2) {
		return true;
	}

	Set<Statement> set1 = toSet(model1);
	Model set2 = toModel(model2);
	// Compare the number of statements in both sets
	if (set1.size() != set2.size()) {
		return false;
	}

	return isSubsetInternal(set1, set2);
}
 
Example 6
Source File: RDFWriterTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void testPerformanceInternal(boolean storeParsedStatements) throws Exception {

		Random prng = new Random(this.getClass().getName().hashCode());
		Model model = new LinkedHashModel();

		for (int i = 0; i < 10000; i++) {

			Value obj = potentialObjects.get(prng.nextInt(potentialObjects.size()));
			if (obj == litBigPlaceholder) {
				StringBuilder big = new StringBuilder();
				int len = 25000 + prng.nextInt(5000);
				for (int j = 0; j < len; j++) {
					big.append(((char) (32 + prng.nextInt(90))));
				}
				obj = vf.createLiteral(big.toString());
			}

			IRI pred = potentialPredicates.get(prng.nextInt(potentialPredicates.size()));
			while (obj instanceof Triple && pred.equals(RDF.TYPE)) {
				// Avoid statements "x rdf:type <<triple>>" as those use the shorter syntax in RDFXMLPrettyWriter
				// and the writer produces invalid XML in that case. Even though the RDF* triples are encoded as
				// valid IRIs, XML has limitations on what characters may form an XML tag name and thus a limitation
				// on what IRIs may be used in predicates (predicates are XML tags) or the short form of rdf:type
				// (where the type is also an XML tag).
				obj = potentialObjects.get(prng.nextInt(potentialObjects.size()));
			}
			model.add(potentialSubjects.get(prng.nextInt(potentialSubjects.size())),
					pred, obj);
		}
		logger.debug("Test class: " + this.getClass().getName());
		logger.debug("Test statements size: " + model.size() + " (" + rdfWriterFactory.getRDFFormat() + ")");
		assertFalse("Did not generate any test statements", model.isEmpty());

		File testFile = tempDir.newFile("performancetest." + rdfWriterFactory.getRDFFormat().getDefaultFileExtension());

		try (OutputStream out = new BufferedOutputStream(new FileOutputStream(testFile))) {

			long startWrite = System.currentTimeMillis();
			RDFWriter rdfWriter = rdfWriterFactory.getWriter(out);
			setupWriterConfig(rdfWriter.getWriterConfig());
			// Test prefixed URIs for only some of the URIs available
			rdfWriter.startRDF();
			rdfWriter.handleNamespace(RDF.PREFIX, RDF.NAMESPACE);
			rdfWriter.handleNamespace(SKOS.PREFIX, SKOS.NAMESPACE);
			rdfWriter.handleNamespace(FOAF.PREFIX, FOAF.NAMESPACE);
			rdfWriter.handleNamespace(EARL.PREFIX, EARL.NAMESPACE);
			rdfWriter.handleNamespace("ex", exNs);

			for (Statement nextSt : model) {
				rdfWriter.handleStatement(nextSt);
			}

			rdfWriter.endRDF();
			long endWrite = System.currentTimeMillis();
			logger.debug(
					"Write took: " + (endWrite - startWrite) + " ms (" + rdfWriterFactory.getRDFFormat() + ")");
			logger.debug("File size (bytes): " + testFile.length());

		}

		try (InputStream in = new BufferedInputStream(new FileInputStream(testFile))) {

			RDFParser rdfParser = rdfParserFactory.getParser();
			setupParserConfig(rdfParser.getParserConfig());
			rdfParser.setValueFactory(vf);
			Model parsedModel = new LinkedHashModel();
			if (storeParsedStatements) {
				rdfParser.setRDFHandler(new StatementCollector(parsedModel));
			}
			long startParse = System.currentTimeMillis();
			rdfParser.parse(in, "foo:bar");
			long endParse = System.currentTimeMillis();
			logger.debug(
					"Parse took: " + (endParse - startParse) + " ms (" + rdfParserFactory.getRDFFormat() + ")");

			if (storeParsedStatements) {
				if (model.size() != parsedModel.size()) {
					if (model.size() < 1000) {
						boolean originalIsSubset = Models.isSubset(model, parsedModel);
						boolean parsedIsSubset = Models.isSubset(parsedModel, model);
						logger.debug("originalIsSubset=" + originalIsSubset);
						logger.debug("parsedIsSubset=" + parsedIsSubset);

//						System.out.println("Written statements=>");
//						IOUtils.writeLines(IOUtils.readLines(new FileInputStream(testFile)), "\n", System.out);
//						System.out.println("Parsed statements=>");
//						Rio.write(parsedModel, System.out, RDFFormat.NQUADS);
					}
				}
				assertEquals(
						"Unexpected number of statements, expected " + model.size() + " found " + parsedModel.size(),
						model.size(), parsedModel.size());

				if (rdfParser.getRDFFormat().supportsNamespaces()) {
					assertTrue("Expected at least 5 namespaces, found " + parsedModel.getNamespaces().size(),
							parsedModel.getNamespaces().size() >= 5);
					assertEquals(exNs, parsedModel.getNamespace("ex").get().getName());
				}
			}
		}
	}