org.eclipse.rdf4j.rio.WriterConfig Java Examples

The following examples show how to use org.eclipse.rdf4j.rio.WriterConfig. 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: SpinRendererTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static String toRDF(StatementCollector stmts) throws RDFHandlerException {
	WriterConfig config = new WriterConfig();
	config.set(BasicWriterSettings.PRETTY_PRINT, false);
	StringBuilderWriter writer = new StringBuilderWriter();
	final RDFWriter rdfWriter = Rio.createWriter(RDFFormat.TURTLE, writer);
	rdfWriter.setWriterConfig(config);

	rdfWriter.startRDF();
	for (Map.Entry<String, String> entry : stmts.getNamespaces().entrySet()) {
		rdfWriter.handleNamespace(entry.getKey(), entry.getValue());
	}
	for (final Statement st : stmts.getStatements()) {
		rdfWriter.handleStatement(st);
	}
	rdfWriter.endRDF();

	writer.close();
	return writer.toString();
}
 
Example #2
Source File: PropertyShape.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
String describe(SailRepositoryConnection connection, Resource resource) {
	GraphQuery graphQuery = connection.prepareGraphQuery("describe ?a where {BIND(?resource as ?a)}");
	graphQuery.setBinding("resource", resource);

	try (Stream<Statement> stream = graphQuery.evaluate().stream()) {

		LinkedHashModel statements = stream.collect(Collectors.toCollection(LinkedHashModel::new));
		statements.setNamespace(SHACL.PREFIX, SHACL.NAMESPACE);

		WriterConfig config = new WriterConfig();
		config.set(BasicWriterSettings.PRETTY_PRINT, true);
		config.set(BasicWriterSettings.INLINE_BLANK_NODES, true);

		StringWriter stringWriter = new StringWriter();

		Rio.write(statements, stringWriter, RDFFormat.TURTLE, config);

		return stringWriter.toString();
	}
}
 
Example #3
Source File: JSONParserParseTest.java    From Halyard with Apache License 2.0 6 votes vote down vote up
@Test
public void testParse() throws Exception {
    Model transformedModel = new LinkedHashModel();
    RDFParser parser = new JSONParser();
    parser.setValueFactory(SimpleValueFactory.getInstance());
    parser.set(JSONParser.GENERATE_ONTOLOGY, true);
    parser.setRDFHandler(new ContextStatementCollector(transformedModel, SimpleValueFactory.getInstance()));
    parser.parse(JSONParserParseTest.class.getResourceAsStream(parameter + ".json"), "http://testParse/"+parameter + "/");

    WriterConfig wc = new WriterConfig();
    wc.set(BasicWriterSettings.PRETTY_PRINT, true);
    System.out.println("-------------- " + parameter + " ------------------");
    Rio.write(transformedModel, System.out, RDFFormat.TURTLE, wc);

    Model expectedModel = Rio.parse(JSONParserParseTest.class.getResourceAsStream(parameter + ".ttl"), "http://testParse/" + parameter + "/", RDFFormat.TURTLE);

    JSONParserParseTest.assertEquals(expectedModel, transformedModel);
}
 
Example #4
Source File: HttpSparqlHandler.java    From Halyard with Apache License 2.0 6 votes vote down vote up
/**
 * @param connection       connection to Sail repository
 * @param storedQueries    pre-defined stored SPARQL query templates
 * @param writerProperties RDF4J RIO WriterConfig properties
 * @param verbose          true when verbose mode enabled, otherwise false
 */
@SuppressWarnings("unchecked")
public HttpSparqlHandler(SailRepositoryConnection connection, Properties storedQueries, Properties writerProperties, boolean verbose) {
    this.connection = connection;
    if (!verbose) {
        // Verbose mode disabled --> logs with level lower than WARNING will be discarded
        LOGGER.setLevel(Level.WARNING);
    }
    this.storedQueries = storedQueries;
    this.writerConfig = new WriterConfig();
    if (writerProperties != null) {
        for (Map.Entry<Object, Object> me : writerProperties.entrySet()) {
            writerConfig.set((RioSetting) getStaticField(me.getKey().toString()), getStaticField(me.getValue().toString()));
        }
    }
}
 
Example #5
Source File: QueryResultsOutputUtil.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Writes the results of a {@link QueryResultStream} to the output stream as JSON until the
 * shutdown signal is set.
 *
 * @param out - The stream the JSON will be written to. (not null)
 * @param query - The parsed SPARQL Query whose results are being output. This
 *   object is used to figure out which bindings may appear. (not null)
 * @param resultsStream - The results stream that will be polled for results to
 *   write to {@code out}. (not null)
 * @param shutdownSignal - Setting this signal will cause the thread that
 *   is processing this function to finish and leave. (not null)
 * @throws TupleQueryResultHandlerException A problem was encountered while
 *   writing the JSON to the output stream.
 * @throws IllegalStateException The {@code resultsStream} is closed.
 * @throws RyaStreamsException Could not fetch the next set of results.
 */
public static void toBindingSetJSONFile(
        final OutputStream out,
        final TupleExpr query,
        final QueryResultStream<VisibilityBindingSet> resultsStream,
        final AtomicBoolean shutdownSignal) throws TupleQueryResultHandlerException, IllegalStateException, RyaStreamsException {
    requireNonNull(out);
    requireNonNull(query);
    requireNonNull(resultsStream);
    requireNonNull(shutdownSignal);

    // Create a writer that does not pretty print.
    final SPARQLResultsJSONWriter writer = new SPARQLResultsJSONWriter(out);
    final WriterConfig config = writer.getWriterConfig();
    config.set(BasicWriterSettings.PRETTY_PRINT, false);

    // Start the JSON and enumerate the possible binding names.
    writer.startQueryResult( Lists.newArrayList(query.getBindingNames()) );

    while(!shutdownSignal.get()) {
        for(final VisibilityBindingSet result : resultsStream.poll(1000)) {
            writer.handleSolution(result);
        }
    }

    writer.endQueryResult();
}
 
Example #6
Source File: Verify.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Write SHACL validation report to a file. File extension is used to select the serialization format, TTL is used
 * as default.
 *
 * @param model      report
 * @param reportFile file name
 */
private void writeReport(Model model, String reportFile) {
	WriterConfig cfg = new WriterConfig();
	cfg.set(BasicWriterSettings.PRETTY_PRINT, true);
	cfg.set(BasicWriterSettings.INLINE_BLANK_NODES, true);

	RDFFormat format = Rio.getParserFormatForFileName(reportFile).orElse(RDFFormat.TURTLE);

	try (Writer w = Files.newBufferedWriter(Paths.get(reportFile))) {
		Rio.write(model, w, format, cfg);
	} catch (IOException ex) {
		writeError("Could not write report to " + reportFile, ex);
	}
}
 
Example #7
Source File: SimpleOntology.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public @Nonnull OutputStream asJsonLD(boolean skolemize, OutputStream outputStream) throws MobiOntologyException {
    WriterConfig config = new WriterConfig();
    try {
        org.eclipse.rdf4j.model.Model sesameModel = asSesameModel();
        if (skolemize) {
            sesameModel = transformer.sesameModel(bNodeService.skolemize(transformer.mobiModel(sesameModel)));
        }
        Rio.write(sesameModel, outputStream, RDFFormat.JSONLD, config);
    } catch (RDFHandlerException e) {
        throw new MobiOntologyException("Error while parsing Ontology.");
    }

    return outputStream;
}
 
Example #8
Source File: ArrangedWriterTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testWriteRepeatedInlineBlankNode() {
	Model model = new ModelBuilder().subject(exNs + "subject")
			.add(vf.createIRI(exNs, "rel1"), bnode1)
			.add(vf.createIRI(exNs, "rel2"), bnode1)
			.add(vf.createIRI(exNs, "rel3"), bnode2)
			.subject(bnode1)
			.add(RDFS.LABEL, "the bnode1")
			.subject(bnode2)
			.add(RDFS.LABEL, "the bnode2")
			.build();

	model.setNamespace(RDFS.NS);
	model.setNamespace("ex", exNs);

	StringWriter stringWriter = new StringWriter();
	BufferedWriter writer = new BufferedWriter(stringWriter);
	WriterConfig config = new WriterConfig();
	config.set(BasicWriterSettings.INLINE_BLANK_NODES, true);
	Rio.write(model, writer, RDFFormat.TURTLE, config);

	String sep = System.lineSeparator();
	String expectedResult = "@prefix ex: <http://example.org/> ." + sep +
			"@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> ." + sep +
			"@prefix xsd: <http://www.w3.org/2001/XMLSchema#> ." + sep + sep +
			"ex:subject ex:rel1 _:bnode1 ." + sep + sep +
			"_:bnode1 rdfs:label \"the bnode1\" ." + sep + sep +
			"ex:subject ex:rel2 _:bnode1;" + sep +
			"  ex:rel3 [" + sep +
			"      rdfs:label \"the bnode2\"" + sep +
			"    ] ." + sep;

	assertEquals(expectedResult, stringWriter.toString());
}
 
Example #9
Source File: RDFJSONWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void modelToRdfJsonInternal(final Model graph, final WriterConfig writerConfig,
		final JsonGenerator jg) throws IOException, JsonGenerationException {
	if (writerConfig.get(BasicWriterSettings.PRETTY_PRINT)) {
		// SES-2011: Always use \n for consistency
		Indenter indenter = DefaultIndenter.SYSTEM_LINEFEED_INSTANCE;
		// By default Jackson does not pretty print, so enable this unless
		// PRETTY_PRINT setting is disabled
		DefaultPrettyPrinter pp = new DefaultPrettyPrinter().withArrayIndenter(indenter)
				.withObjectIndenter(indenter);
		jg.setPrettyPrinter(pp);
	}
	jg.writeStartObject();
	for (final Resource nextSubject : graph.subjects()) {
		jg.writeObjectFieldStart(RDFJSONWriter.resourceToString(nextSubject));
		for (final IRI nextPredicate : graph.filter(nextSubject, null, null).predicates()) {
			jg.writeArrayFieldStart(nextPredicate.stringValue());
			for (final Value nextObject : graph.filter(nextSubject, nextPredicate, null).objects()) {
				// contexts are optional, so this may return empty in some
				// scenarios depending on the interpretation of the way contexts
				// work
				final Set<Resource> contexts = graph.filter(nextSubject, nextPredicate, nextObject).contexts();

				RDFJSONWriter.writeObject(nextObject, contexts, jg);
			}
			jg.writeEndArray();
		}
		jg.writeEndObject();
	}
	jg.writeEndObject();
}
 
Example #10
Source File: AbstractShaclTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void printCurrentState(SailRepository shaclRepository) {
	if (!fullLogging) {
		return;
	}

	try (SailRepositoryConnection connection = shaclRepository.getConnection()) {

		if (connection.isEmpty()) {
			System.out.println("### CURRENT REPOSITORY STATE ###");
			System.out.println("   EMPTY!");
			System.out.println("################################################\n");
		} else {

			try (Stream<Statement> stream = connection.getStatements(null, null, null, false).stream()) {
				LinkedHashModel model = stream.collect(Collectors.toCollection(LinkedHashModel::new));
				model.setNamespace("ex", "http://example.com/ns#");
				model.setNamespace(FOAF.PREFIX, FOAF.NAMESPACE);
				model.setNamespace(XMLSchema.PREFIX, XMLSchema.NAMESPACE);
				model.setNamespace(RDF.PREFIX, RDF.NAMESPACE);
				model.setNamespace(RDFS.PREFIX, RDFS.NAMESPACE);

				WriterConfig writerConfig = new WriterConfig();
				writerConfig.set(BasicWriterSettings.PRETTY_PRINT, true);
				writerConfig.set(BasicWriterSettings.INLINE_BLANK_NODES, true);
				System.out.println("### CURRENT REPOSITORY STATE ###");
				Rio.write(model, System.out, RDFFormat.TURTLE, writerConfig);
				System.out.println("################################################\n");

			}
		}

	}
}
 
Example #11
Source File: AbstractShaclTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void printResults(ValidationReport report) {
	if (!fullLogging) {
		return;
	}
	System.out.println("\n############################################");
	System.out.println("\tValidation Report\n");
	Model validationReport = report.asModel();

	WriterConfig writerConfig = new WriterConfig();
	writerConfig.set(BasicWriterSettings.PRETTY_PRINT, true);
	writerConfig.set(BasicWriterSettings.INLINE_BLANK_NODES, true);

	Rio.write(validationReport, System.out, RDFFormat.TURTLE, writerConfig);
	System.out.println("\n############################################");
}
 
Example #12
Source File: JSONLDHierarchicalWriterTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Before
public void setup() {
	model = new LinkedHashModel();
	writerConfig = new WriterConfig();
	writerConfig.set(JSONLDSettings.HIERARCHICAL_VIEW, true);
}
 
Example #13
Source File: TriGPrettyWriterTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected void setupWriterConfig(WriterConfig config) {
	config.set(BasicWriterSettings.PRETTY_PRINT, true);
}
 
Example #14
Source File: RDFXMLWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
protected void writeHeader() throws IOException {
	try {
		// This export format needs the RDF namespace to be defined, add a
		// prefix for it if there isn't one yet.
		setNamespace(RDF.PREFIX, RDF.NAMESPACE);

		WriterConfig writerConfig = getWriterConfig();
		quote = writerConfig.get(XMLWriterSettings.USE_SINGLE_QUOTES) ? '\'' : '\"';
		entityQuote = writerConfig.get(XMLWriterSettings.QUOTES_TO_ENTITIES_IN_TEXT);

		if (writerConfig.get(XMLWriterSettings.INCLUDE_XML_PI)) {
			String str = (quote == '\"') ? "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
					: "<?xml version='1.0' encoding='UTF-8'?>\n";
			writer.write(str);
		}

		if (writerConfig.get(XMLWriterSettings.INCLUDE_ROOT_RDF_TAG)) {
			writeStartOfStartTag(RDF.NAMESPACE, "RDF");

			if (defaultNamespace != null) {
				writeNewLine();
				writeIndent();
				writeQuotedAttribute("xmlns", defaultNamespace);
			}

			for (Map.Entry<String, String> entry : namespaceTable.entrySet()) {
				String name = entry.getKey();
				String prefix = entry.getValue();

				writeNewLine();
				writeIndent();
				writeQuotedAttribute("xmlns:" + prefix, name);
			}

			if (baseIRI != null && writerConfig.get(BasicWriterSettings.BASE_DIRECTIVE)) {
				writeNewLine();
				writeIndent();
				writeQuotedAttribute("xml:base", baseIRI.toString());
			}

			writeEndOfStartTag();
		}

		writeNewLine();
	} finally {
		headerWritten = true;
	}
}
 
Example #15
Source File: RDFXMLWriterTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected void setupWriterConfig(WriterConfig config) {
	config.set(BasicWriterSettings.PRETTY_PRINT, false);
}
 
Example #16
Source File: RDFXMLPrettyWriterBackgroundTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected void setupWriterConfig(WriterConfig config) {
	config.set(BasicWriterSettings.PRETTY_PRINT, true);
}
 
Example #17
Source File: RDFXMLPrettyWriterTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected void setupWriterConfig(WriterConfig config) {
	config.set(BasicWriterSettings.PRETTY_PRINT, true);
}
 
Example #18
Source File: RDFXMLWriterBackgroundTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected void setupWriterConfig(WriterConfig config) {
	config.set(BasicWriterSettings.PRETTY_PRINT, false);
}
 
Example #19
Source File: JSONLDWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void endRDF() throws RDFHandlerException {
	checkWritingStarted();
	final JSONLDInternalRDFParser serialiser = new JSONLDInternalRDFParser();
	try {
		Object output = JsonLdProcessor.fromRDF(model, serialiser);

		final JSONLDMode mode = getWriterConfig().get(JSONLDSettings.JSONLD_MODE);

		final JsonLdOptions opts = new JsonLdOptions();
		// opts.addBlankNodeIDs =
		// getWriterConfig().get(BasicParserSettings.PRESERVE_BNODE_IDS);
		WriterConfig writerConfig = getWriterConfig();
		opts.setCompactArrays(writerConfig.get(JSONLDSettings.COMPACT_ARRAYS));
		opts.setProduceGeneralizedRdf(writerConfig.get(JSONLDSettings.PRODUCE_GENERALIZED_RDF));
		opts.setUseRdfType(writerConfig.get(JSONLDSettings.USE_RDF_TYPE));
		opts.setUseNativeTypes(writerConfig.get(JSONLDSettings.USE_NATIVE_TYPES));
		// opts.optimize = getWriterConfig().get(JSONLDSettings.OPTIMIZE);

		if (writerConfig.get(JSONLDSettings.HIERARCHICAL_VIEW)) {
			output = JSONLDHierarchicalProcessor.fromJsonLdObject(output);
		}

		if (baseURI != null && writerConfig.get(BasicWriterSettings.BASE_DIRECTIVE)) {
			opts.setBase(baseURI);
		}
		if (mode == JSONLDMode.EXPAND) {
			output = JsonLdProcessor.expand(output, opts);
		}
		// TODO: Implement inframe in JSONLDSettings
		final Object inframe = null;
		if (mode == JSONLDMode.FLATTEN) {
			output = JsonLdProcessor.flatten(output, inframe, opts);
		}
		if (mode == JSONLDMode.COMPACT) {
			final Map<String, Object> ctx = new LinkedHashMap<>();
			addPrefixes(ctx, model.getNamespaces());
			final Map<String, Object> localCtx = new HashMap<>();
			localCtx.put(JsonLdConsts.CONTEXT, ctx);

			output = JsonLdProcessor.compact(output, localCtx, opts);
		}
		if (writerConfig.get(BasicWriterSettings.PRETTY_PRINT)) {
			JsonUtils.writePrettyPrint(writer, output);
		} else {
			JsonUtils.write(writer, output);
		}

	} catch (JsonLdError | IOException e) {
		throw new RDFHandlerException("Could not render JSONLD", e);
	}
}
 
Example #20
Source File: JSONLDWriterBackgroundTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected void setupWriterConfig(WriterConfig config) {
	super.setupWriterConfig(config);
	config.set(JSONLDSettings.JSONLD_MODE, JSONLDMode.COMPACT);
}
 
Example #21
Source File: TriGWriterBackgroundTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected void setupWriterConfig(WriterConfig config) {
	config.set(BasicWriterSettings.PRETTY_PRINT, false);
}
 
Example #22
Source File: JSONLDWriterTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected void setupWriterConfig(WriterConfig config) {
	super.setupWriterConfig(config);
	config.set(JSONLDSettings.JSONLD_MODE, JSONLDMode.COMPACT);
}
 
Example #23
Source File: AbstractQueryResultWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void setWriterConfig(WriterConfig config) {
	this.writerConfig = config;
}
 
Example #24
Source File: MappingRecordServiceTest.java    From mobi with GNU Affero General Public License v3.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
    recordService = new SimpleMappingRecordService();
    deleteActivity = deleteActivityFactory.createNew(VALUE_FACTORY.createIRI("http://test.org/activity/delete"));
    WriterConfig config = new WriterConfig();
    config.set(JSONLDSettings.JSONLD_MODE, JSONLDMode.FLATTEN);
    InputStream testMapping = getClass().getResourceAsStream("/newestMapping.ttl");
    mappingModel = MODEL_FACTORY.createModel(Values.mobiModel(Rio.parse(testMapping, "", RDFFormat.TURTLE)));
    mappingJsonLd = new ByteArrayOutputStream();
    Rio.write(Values.sesameModel(mappingModel), mappingJsonLd, RDFFormat.JSONLD, config);

    user = userFactory.createNew(VALUE_FACTORY.createIRI("http://test.org/user"));
    headCommit = commitFactory.createNew(commitIRI);
    branch = branchFactory.createNew(branchIRI);
    branch.setHead(headCommit);
    branch.setProperty(VALUE_FACTORY.createLiteral("Test Branch"), VALUE_FACTORY.createIRI(_Thing.title_IRI));

    testRecord = recordFactory.createNew(recordIRI);
    testRecord.setProperty(VALUE_FACTORY.createLiteral("Test Record"), VALUE_FACTORY.createIRI(_Thing.title_IRI));
    testRecord.setCatalog(catalogFactory.createNew(catalogIRI));
    testRecord.setBranch(Collections.singleton(branch));
    testRecord.setMasterBranch(branch);

    MockitoAnnotations.initMocks(this);

    when(configProvider.getRepository()).thenReturn(repository);

    when(repository.getConnection()).thenReturn(connection);

    when(connection.prepareTupleQuery(anyString())).thenReturn(tupleQuery);
    when(connection.getStatements(eq(null), eq(VALUE_FACTORY.createIRI(Policy.relatedResource_IRI)), any(IRI.class))).thenReturn(results);

    when(tupleQuery.evaluate()).thenReturn(tupleQueryResult);

    when(tupleQueryResult.hasNext()).thenReturn(true, false);
    when(tupleQueryResult.next()).thenReturn(bindingSet);

    when(bindingSet.getBinding(anyString())).thenReturn(Optional.of(binding));

    when(binding.getValue()).thenReturn(VALUE_FACTORY.createLiteral("urn:record"),
            VALUE_FACTORY.createLiteral("urn:master"), VALUE_FACTORY.createLiteral("urn:user"));

    when(results.hasNext()).thenReturn(true);
    when(results.next()).thenReturn(statement);

    when(statement.getSubject()).thenReturn(recordPolicyIRI);

    when(xacmlPolicyManager.addPolicy(any(XACMLPolicy.class))).thenReturn(recordPolicyIRI);

    when(utilsService.optObject(any(IRI.class), any(OrmFactory.class), eq(connection))).thenReturn(Optional.of(testRecord));
    when(utilsService.getBranch(eq(testRecord), eq(branchIRI), any(OrmFactory.class), eq(connection))).thenReturn(branch);
    when(utilsService.getHeadCommitIRI(eq(branch))).thenReturn(commitIRI);
    doReturn(Stream.of(commitIRI).collect(Collectors.toList()))
            .when(utilsService).getCommitChain(eq(commitIRI), eq(false), any(RepositoryConnection.class));
    when(utilsService.getExpectedObject(eq(commitIRI), any(OrmFactory.class), eq(connection))).thenReturn(headCommit);

    when(mappingWrapper.getModel()).thenReturn(mappingModel);
    when(mappingWrapper.getId()).thenReturn(mappingId);

    when(manager.createMapping(any(Model.class))).thenReturn(mappingWrapper);
    when(manager.createMapping(any(InputStream.class), any(RDFFormat.class))).thenReturn(mappingWrapper);

    injectOrmFactoryReferencesIntoService(recordService);
    recordService.setManager(manager);
    recordService.setUtilsService(utilsService);
    recordService.setVf(VALUE_FACTORY);
    recordService.setProvUtils(provUtils);
    recordService.setVersioningManager(versioningManager);
    recordService.setMergeRequestManager(mergeRequestManager);
    recordService.setPolicyManager(xacmlPolicyManager);
    recordService.setEngineManager(engineManager);
    recordService.setCatalogConfigProvider(configProvider);
}
 
Example #25
Source File: OntologyRecordServiceTest.java    From mobi with GNU Affero General Public License v3.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
    recordService = new SimpleOntologyRecordService();
    deleteActivity = deleteActivityFactory.createNew(VALUE_FACTORY.createIRI("http://test.org/activity/delete"));
    WriterConfig config = new WriterConfig();
    config.set(JSONLDSettings.JSONLD_MODE, JSONLDMode.FLATTEN);
    importedOntologyIRI = VALUE_FACTORY.createIRI("http://test.org/ontology/IRI");
    InputStream testOntology = getClass().getResourceAsStream("/test-ontology.ttl");
    ontologyModel = MODEL_FACTORY.createModel(Values.mobiModel(Rio.parse(testOntology, "", RDFFormat.TURTLE)));
    ontologyJsonLd = new ByteArrayOutputStream();
    Rio.write(Values.sesameModel(ontologyModel), ontologyJsonLd, RDFFormat.JSONLD, config);

    user = userFactory.createNew(VALUE_FACTORY.createIRI("http://test.org/user"));
    headCommit = commitFactory.createNew(commitIRI);
    branch = branchFactory.createNew(branchIRI);
    branch.setHead(headCommit);
    branch.setProperty(VALUE_FACTORY.createLiteral("Test Record"), VALUE_FACTORY.createIRI(_Thing.title_IRI));

    Model deletions = MODEL_FACTORY.createModel();
    deletions.add(VALUE_FACTORY.createIRI("http://test.com#sub"), VALUE_FACTORY.createIRI(_Thing.description_IRI),
            VALUE_FACTORY.createLiteral("Description"));

    difference = new Difference.Builder()
            .additions(MODEL_FACTORY.createModel())
            .deletions(deletions)
            .build();


    tag = tagFactory.createNew(tagIRI);
    tag.setVersionedDistribution(Collections.singleton(distributionFactory.createNew(distributionIRI)));

    testRecord = recordFactory.createNew(testIRI);
    testRecord.setProperty(VALUE_FACTORY.createLiteral("Test Record"), VALUE_FACTORY.createIRI(_Thing.title_IRI));
    testRecord.setCatalog(catalogFactory.createNew(catalogId));
    testRecord.setBranch(Collections.singleton(branch));
    testRecord.setVersion(Collections.singleton(tag));
    testRecord.setLatestVersion(tag);
    testRecord.setBranch(Collections.singleton(branch));
    testRecord.setMasterBranch(branchFactory.createNew(masterBranchIRI));
    testRecord.setOntologyIRI(testIRI);

    MockitoAnnotations.initMocks(this);
    when(ontologyId1.getOntologyIRI()).thenReturn(Optional.empty());
    when(ontologyId1.getOntologyIdentifier()).thenReturn(importedOntologyIRI);
    when(ontologyId2.getOntologyIRI()).thenReturn(Optional.of(importedOntologyIRI));
    when(ontologyManager.ontologyIriExists(any(IRI.class))).thenReturn(false);
    when(ontologyManager.createOntologyId(any(Model.class))).thenReturn(ontologyId1);
    when(versioningManager.commit(any(IRI.class), any(IRI.class), any(IRI.class), eq(user), anyString(), any(Model.class), any(Model.class))).thenReturn(commitIRI);
    when(utilsService.optObject(any(IRI.class), any(OrmFactory.class), eq(connection))).thenReturn(Optional.of(testRecord));
    when(utilsService.getBranch(eq(testRecord), eq(branchIRI), any(OrmFactory.class), eq(connection))).thenReturn(branch);
    when(utilsService.getHeadCommitIRI(eq(branch))).thenReturn(commitIRI);
    doReturn(Stream.of(commitIRI).collect(Collectors.toList()))
            .when(utilsService).getCommitChain(eq(commitIRI), eq(false), any(RepositoryConnection.class));
    when(utilsService.getExpectedObject(eq(commitIRI), any(OrmFactory.class), eq(connection))).thenReturn(headCommit);
    when(utilsService.getRevisionChanges(eq(commitIRI), eq(connection))).thenReturn(difference);
    when(provUtils.startDeleteActivity(any(User.class), any(IRI.class))).thenReturn(deleteActivity);
    doNothing().when(mergeRequestManager).deleteMergeRequestsWithRecordId(eq(testIRI), any(RepositoryConnection.class));
    doNothing().when(ontologyCache).clearCache(any(Resource.class));
    doNothing().when(ontologyCache).clearCacheImports(any(Resource.class));
    when(xacmlPolicyManager.addPolicy(any(XACMLPolicy.class))).thenReturn(recordPolicyIRI);
    when(connection.getStatements(eq(null), eq(VALUE_FACTORY.createIRI(Policy.relatedResource_IRI)), any(IRI.class))).thenReturn(results);
    when(results.hasNext()).thenReturn(true);
    when(results.next()).thenReturn(statement);
    when(statement.getSubject()).thenReturn(recordPolicyIRI);
    when(configProvider.getRepository()).thenReturn(repository);
    when(repository.getConnection()).thenReturn(connection);
    when(connection.prepareTupleQuery(anyString())).thenReturn(tupleQuery);
    when(tupleQuery.evaluate()).thenReturn(tupleQueryResult);
    when(tupleQueryResult.hasNext()).thenReturn(true, false);
    when(tupleQueryResult.next()).thenReturn(bindingSet);
    when(bindingSet.getBinding(anyString())).thenReturn(Optional.of(binding));
    when(binding.getValue()).thenReturn(VALUE_FACTORY.createLiteral("urn:record"),
            VALUE_FACTORY.createLiteral("urn:master"), VALUE_FACTORY.createLiteral("urn:user"));
    when(sesameTransformer.mobiModel(any(org.eclipse.rdf4j.model.Model.class))).thenAnswer(i -> Values.mobiModel(i.getArgumentAt(0, org.eclipse.rdf4j.model.Model.class)));

    injectOrmFactoryReferencesIntoService(recordService);
    recordService.setOntologyManager(ontologyManager);
    recordService.setUtilsService(utilsService);
    recordService.setVf(VALUE_FACTORY);
    recordService.setModelFactory(MODEL_FACTORY);
    recordService.setProvUtils(provUtils);
    recordService.setOntologyCache(ontologyCache);
    recordService.setVersioningManager(versioningManager);
    recordService.setMergeRequestManager(mergeRequestManager);
    recordService.setPolicyManager(xacmlPolicyManager);
    recordService.setEngineManager(engineManager);
    recordService.setCatalogConfigProvider(configProvider);
    recordService.setSesameTransformer(sesameTransformer);
}
 
Example #26
Source File: ValidationReportTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void nestedLogicalOrSupport() throws IOException {

	SailRepository shaclSail = Utils.getInitializedShaclRepository("test-cases/or/datatype/shacl.ttl", false);

	try (SailRepositoryConnection connection = shaclSail.getConnection()) {

		connection.begin();
		connection.prepareUpdate(IOUtils.toString(ValidationReportTest.class.getClassLoader()
				.getResourceAsStream("test-cases/or/datatype/invalid/case1/query1.rq"), StandardCharsets.UTF_8))
				.execute();
		connection.commit();
		fail();

	} catch (RepositoryException e) {
		ShaclSailValidationException cause = (ShaclSailValidationException) e.getCause();
		Model actual = cause.validationReportAsModel();

		actual.setNamespace(RDF.PREFIX, RDF.NAMESPACE);
		actual.setNamespace(RDFS.PREFIX, RDFS.NAMESPACE);
		actual.setNamespace("ex", "http://example.com/ns#");

		WriterConfig writerConfig = new WriterConfig();
		writerConfig.set(BasicWriterSettings.INLINE_BLANK_NODES, true);
		writerConfig.set(BasicWriterSettings.PRETTY_PRINT, true);

		Rio.write(actual, System.out, RDFFormat.TURTLE, writerConfig);

		Model expected = Rio.parse(new StringReader(""
				+ "@prefix ex: <http://example.com/ns#> .\n"
				+ "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n"
				+ "@prefix sh: <http://www.w3.org/ns/shacl#> .\n" + "\n"
				+ "[] a sh:ValidationReport;\n" +
				"  sh:conforms false;\n" +
				"  sh:result [ a sh:ValidationResult;\n" +
				"      sh:detail [ a sh:ValidationResult;\n" +
				"          sh:detail [ a sh:ValidationResult;\n" +
				"              sh:focusNode ex:validPerson1;\n" +
				"              sh:resultPath ex:age;\n" +
				"              sh:sourceConstraintComponent sh:DatatypeConstraintComponent;\n" +
				"              sh:sourceShape ex:personShapeAgeLong\n" +
				"            ];\n" +
				"          sh:focusNode ex:validPerson1;\n" +
				"          sh:resultPath ex:age;\n" +
				"          sh:sourceConstraintComponent sh:DatatypeConstraintComponent;\n" +
				"          sh:sourceShape ex:personShapeAgeInteger\n" +
				"        ];\n" +
				"      sh:focusNode ex:validPerson1;\n" +
				"      sh:resultPath ex:age;\n" +
				"      sh:sourceConstraintComponent sh:OrConstraintComponent;\n" +
				"      sh:sourceShape ex:personShapeOr\n" +
				"    ] ." + ""), "", RDFFormat.TURTLE);

		assertTrue(Models.isomorphic(expected, actual));

	}
}
 
Example #27
Source File: TurtleWriterTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected void setupWriterConfig(WriterConfig config) {
	config.set(BasicWriterSettings.PRETTY_PRINT, false);
}
 
Example #28
Source File: N3Writer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public RDFWriter setWriterConfig(WriterConfig config) {
	this.writerConfig = config;
	return this;
}
 
Example #29
Source File: N3Writer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public WriterConfig getWriterConfig() {
	return writerConfig;
}
 
Example #30
Source File: AbstractRDFWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public RDFWriter setWriterConfig(WriterConfig config) {
	this.writerConfig = config;
	return this;
}