Java Code Examples for org.apache.jena.rdf.model.Model#read()

The following examples show how to use org.apache.jena.rdf.model.Model#read() . 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: RoundtripIT.java    From fcrepo-import-export with Apache License 2.0 6 votes vote down vote up
@Test
public void testRoundtripNested() throws Exception {
    final URI containerURI = URI.create(serverAddress + UUID.randomUUID());

    // create a new nested containers
    assertEquals(SC_CREATED, clientBuilder.build().put(containerURI).perform().getStatusCode());
    assertEquals(SC_CREATED, clientBuilder.build().post(containerURI).slug("b")
            .body(new ByteArrayInputStream("content".getBytes("UTF-8")), "text/plain").perform().getStatusCode());
    assertEquals(SC_CREATED, clientBuilder.build().post(containerURI).slug("a").perform().getStatusCode());

    final Model origModel = ModelFactory.createDefaultModel();
    origModel.read(
            clientBuilder.build().get(containerURI).accept("application/n-triples").perform().getBody(), "", "N3");

    roundtrip(containerURI, true);

    final Model roundtrippedModel = ModelFactory.createDefaultModel();
    roundtrippedModel.read(
            clientBuilder.build().get(containerURI).accept("application/n-triples").perform().getBody(), "", "N3");

    assertIdenticalGraphs(origModel, roundtrippedModel);
}
 
Example 2
Source File: RuleExample.java    From shacl with Apache License 2.0 6 votes vote down vote up
/**
 * Loads an example SHACL-AF (rules) file and execute it against the data.
 */
public static void main(String[] args) throws Exception {

    // Load the main data model that contains rule(s)
    Model dataModel = JenaUtil.createMemoryModel();
    dataModel.read(RuleExample.class.getResourceAsStream("sh/tests/rules/triple/rectangle.test.ttl"), "urn:dummy",
            FileUtils.langTurtle);

    // Perform the rule calculation, using the data model
    // also as the rule model - you may have them separated
    Model result = RuleUtil.executeRules(dataModel, dataModel, null, null);

    // you may want to add the original data, to make sense of the rule results
    result.add(dataModel);

    // Print rule calculation results
    System.out.println(ModelPrinter.get().print(result));
}
 
Example 3
Source File: ControllerTest.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
@Test
void should_get_for_graphql() throws Exception {

    final String path = basePath + config.getGraphqlConfig().port() + config.getGraphqlConfig().graphQLPath();

    final Envelope envelope = getPath(path, "text/turtle");

    final Model model = ModelFactory.createDefaultModel();
    model.read(envelope.streamBody(), "", "text/turtle");
    assertTrue(model.size() > 0);
    assertEquals(167, model.size());
}
 
Example 4
Source File: W3CTestRunner.java    From shacl with Apache License 2.0 5 votes vote down vote up
private void collectItems(File manifestFile, String baseURI) throws IOException {
	
	String filePath = manifestFile.getAbsolutePath().replaceAll("\\\\", "/");
	int coreIndex = filePath.indexOf("core/");
	if(coreIndex > 0 && !filePath.contains("sparql/core")) {
		filePath = filePath.substring(coreIndex);
	}
	else {
		int sindex = filePath.indexOf("sparql/");
		if(sindex > 0) {
			filePath = filePath.substring(sindex);
		}
	}
	
	Model model = JenaUtil.createMemoryModel();
	model.read(new FileInputStream(manifestFile), baseURI, FileUtils.langTurtle);
	
	for(Resource manifest : model.listSubjectsWithProperty(RDF.type, MF.Manifest).toList()) {
		for(Resource include : JenaUtil.getResourceProperties(manifest, MF.include)) {
			String path = include.getURI().substring(baseURI.length());
			File includeFile = new File(manifestFile.getParentFile(), path);
			if(path.contains("/")) {
				String addURI = path.substring(0, path.indexOf('/'));
				collectItems(includeFile, baseURI + addURI + "/");
			}
			else {
				collectItems(includeFile, baseURI + path);
			}
		}
		for(Resource entries : JenaUtil.getResourceProperties(manifest, MF.entries)) {
			for(RDFNode entry : entries.as(RDFList.class).iterator().toList()) {
				items.add(new Item(entry.asResource(), filePath, manifestFile));
			}
		}
	}
}
 
Example 5
Source File: FunctionTestCaseType.java    From shacl with Apache License 2.0 5 votes vote down vote up
private Graph parseGraph(RDFNode node) {
	Model model = JenaUtil.createDefaultModel();
	if(node.isLiteral()) {
		String str = node.asLiteral().getLexicalForm();
		model.read(new ByteArrayInputStream(str.getBytes()), "urn:x:dummy", FileUtils.langTurtle);
	}
	return model.getGraph();
}
 
Example 6
Source File: ImporterTest.java    From fcrepo-import-export with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultModeRetainsLastModified() throws Exception {
    final ArgumentCaptor<InputStream> streamCapture = ArgumentCaptor.forClass(InputStream.class);
    final Importer importer = new Importer(containerArgs, clientBuilder);
    importer.run();

    verify(putBuilder).body(streamCapture.capture(), isA(String.class));
    final Model model = createDefaultModel();
    model.read(streamCapture.getValue(), "", "JSON-LD");
    final Graph graph = model.getGraph();
    assertTrue(graph.contains(Node.ANY, LAST_MODIFIED_DATE.asNode(), Node.ANY));
}
 
Example 7
Source File: ImporterTest.java    From fcrepo-import-export with Apache License 2.0 5 votes vote down vote up
@Test
public void testLegacyModeStripsLastModified() throws Exception {
    containerArgs.setLegacy(true);
    final ArgumentCaptor<InputStream> streamCapture = ArgumentCaptor.forClass(InputStream.class);
    final Importer importer = new Importer(containerArgs, clientBuilder);
    importer.run();

    verify(putBuilder).body(streamCapture.capture(), isA(String.class));
    final Model model = createDefaultModel();
    model.read(streamCapture.getValue(), "", "JSON-LD");
    final Graph graph = model.getGraph();
    assertFalse(graph.contains(Node.ANY, LAST_MODIFIED_DATE.asNode(), Node.ANY));
}
 
Example 8
Source File: ImporterIT.java    From fcrepo-import-export with Apache License 2.0 5 votes vote down vote up
@Test
public void testImportContainer() throws Exception {
    // import test-indirect

    final URI sourceURI = URI.create("http://localhost:8080/fcrepo/rest");
    final URI parentURI = URI.create(serverAddress + "indirect/1");
    final URI memberURI = URI.create(serverAddress + "indirect/2");
    final String indirectPath = TARGET_DIR + "/test-classes/sample/indirect";

    final Config config = new Config();
    config.setMode("import");
    config.setBaseDirectory(indirectPath);
    config.setPredicates(predicates);
    config.setRdfLanguage(DEFAULT_RDF_LANG);
    config.setResource(serverAddress);
    config.setMap(new String[]{sourceURI.toString(), serverAddress});
    config.setUsername(USERNAME);
    config.setPassword(PASSWORD);

    // run import
    final Importer importer = new Importer(config, clientBuilder);
    importer.run();

    // verify one title and one hasMember
    final FcrepoResponse response = clientBuilder.build().get(parentURI).accept("application/n-triples").perform();
    final Model model = createDefaultModel();
    model.read(response.getBody(), "", "N3");
    response.close();
    final Graph graph = model.getGraph();
    assertTrue("DC title should exist. \n" + graph.toString(), graph.contains(createURI(String.valueOf(parentURI)),
            createURI("http://purl.org/dc/terms/title"), createLiteral("foo")));
    assertTrue("Membership triple should exist.", graph.contains(createURI(String.valueOf(parentURI)),
            createURI("http://pcdm.org/models#hasMember"), createURI(String.valueOf(memberURI))));
}
 
Example 9
Source File: ClassSurfaceForms.java    From NLIWOD with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {

		CLASS_SURFACE_FORMS = DIRECTORY + "class_surface_forms.ttl";

		// create an empty model
		Model inputModel = ModelFactory.createDefaultModel();

		// use the FileManager to find the input file
		InputStream in = FileManager.get().open(DBPEDIA_CLASSE_FILE);
		if (in == null) {
			throw new IllegalArgumentException("File: " + DBPEDIA_CLASSE_FILE + " not found");
		}

		// read the RDF/XML file
		inputModel.read(in, null, "N-TRIPLE");

		Model outputModel = ModelFactory.createDefaultModel();
		QueryExecution qExec = QueryExecutionFactory
				.create("SELECT ?s ?label WHERE{?s a <http://www.w3.org/2002/07/owl#Class>."
						+ " ?s <http://www.w3.org/2000/01/rdf-schema#label> ?label. "
						+ "FILTER (lang(?label) = \"en\")}", inputModel);
		ResultSet rs = qExec.execSelect();
		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			Resource uri = qs.get("?s").asResource();
			RDFNode label = qs.get("?label");
			StatementImpl s = new StatementImpl(uri, RDFS.label, label);
			outputModel.add(s);

		}

		qExec.close();

		FileOutputStream outputFile = new FileOutputStream(CLASS_SURFACE_FORMS);
		RDFDataMgr.write(outputFile, outputModel, RDFFormat.NTRIPLES);

	}
 
Example 10
Source File: JenaDriver.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void read(final String modelPath) throws IOException {
	final Model defaultModel = ModelFactory.createDefaultModel();
	defaultModel.read(modelPath);

	// run inferencing if required
	if (inferencing) {
		final Reasoner reasoner = ReasonerRegistry.getRDFSSimpleReasoner();
		model = ModelFactory.createInfModel(reasoner, defaultModel);
	} else {
		model = defaultModel;
	}
}
 
Example 11
Source File: OWLQLSPARQLCompiler.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * <p>
 * Usage: queryFile ontologyFile (ontologyFile)* 
 * </p>
 * <p>
 * where
 *   <ul>
 *   	<li>queryFile: indicates the location of a semicolon separated file containing the input SPARQL queries. </li>
 *      <li>ontologyFile: indicates the location of the TBox files</li>
 *   </ul> 
 * </p>
 * @param args
 */
public static void main(String[] args) throws Exception {
	if (args.length<2) {
		logger.error("At least two arguments expected: queryFile ontologyFile (ontologyFile)* ");
		return;
	}
	logger.debug("START");
	File queryFile = new File(args[0]);
	File[] ontFiles = new File[args.length-1];
	for (int i=1; i<args.length;i++) {
		ontFiles[i-1] = new File(args[i]);
	}
	List<Query> queries = OCUtils.loadQueries(queryFile);
	Model tboxmodel = ModelFactory.createDefaultModel();
	for (File f: ontFiles) {
		tboxmodel.read(f.toURI().toString());
	}
	
	int count = 1;
	OWLQLSPARQLCompiler compiler = new OWLQLSPARQLCompiler(tboxmodel, null, null);
	for (Query q: queries) {
		Query eq = compiler.compile(q);
		StringBuffer buf =new StringBuffer();
		buf.append(eq+"\n");
		System.out.println("# Query #"+count);
		System.out.println(buf+";");
		count++;
	}
}
 
Example 12
Source File: RmlRdfCreator.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void sendQuads(RdfSerializer saver, DataSet dataSet, Consumer<String> status)
  throws LogStorageFailedException {
  RdfDataSourceFactory dataSourceFactory = dataSet.getDataSource();

  final Model model = ModelFactory.createDefaultModel();
  try {
    model.read(new ByteArrayInputStream(rdfData.getBytes(StandardCharsets.UTF_8)), null, "JSON-LD");
  } catch (Exception e) {
    throw new LogStorageFailedException(e);
  }

  final RmlMappingDocument rmlMappingDocument = rmlBuilder.fromRdf(model, dataSourceFactory::apply);
  if (rmlMappingDocument.getErrors().size() > 0) {
    throw new LogStorageFailedException(
      "failure: " + String.join("\nfailure: ", rmlMappingDocument.getErrors()) + "\n"
    );
  }
  //FIXME: trigger onprefix for all rml prefixes
  //FIXME: store rml and retrieve it from tripleStore when mapping

  Stream<Quad> triples = rmlMappingDocument.execute(new ReportingErrorHandler(status));
  Iterator<Quad> iterator = triples.iterator();
  while (iterator.hasNext()) {
    Quad triple = iterator.next();
    saver.onQuad(
      triple.getSubject().getUri().get(),
      triple.getPredicate().getUri().get(),
      triple.getObject().getContent(),
      triple.getObject().getLiteralType().orElse(null),
      triple.getObject().getLiteralLanguage().orElse(null),
      baseUri
    );
  }
}
 
Example 13
Source File: RDFToTopicMapConverter.java    From ontopia with Apache License 2.0 5 votes vote down vote up
private void doConversion(URL url, String syntax)
  throws JenaException, IOException {

  if (mappings != null && (syntax == null || syntax.equals("RDF/XML")))
    RDFUtils.parseRDFXML(url, new ToTMStatementHandler());

  else {
    Model model = ModelFactory.createDefaultModel();
    model.read(url.openStream(), url.toString(), syntax);
    if (mappings == null)
      buildMappings(model);

    doConversion(model);
  }
}
 
Example 14
Source File: RDFConverter.java    From IGUANA with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws FileNotFoundException {
		Model m = ModelFactory.createDefaultModel();
		m.read(new FileInputStream("swdf.nt"), "http://data.semanticweb.org", "NT");
		m.write(new FileOutputStream("swdf.ttl"), "TTL");
//		for(String arg : args) {
//			Model m = ModelFactory.createDefaultModel();
//			System.out.println(arg);
//			try {
//				m.read(new FileInputStream("/home/minimal/lemming/Lemming/"+arg), "http://data.semanticweb.org", "RDF/XML");
//				m.write(new FileOutputStream("swdf.nt", true), "NT");
//			}catch(Exception e) {
//				e.printStackTrace();
//			}
//		}
	}
 
Example 15
Source File: SolidUtilities.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the contents of a URL to produce an RDF model.
 */
public Model getModel(String url) throws IOException {
  HttpRequestFactory factory = TRANSPORT.createRequestFactory();

  HttpRequest rootGetRequest = factory.buildGetRequest(
      new GenericUrl(url));
  HttpHeaders headers = new HttpHeaders();
  headers.setCookie(authCookie);
  headers.setAccept("text/turtle");
  rootGetRequest.setHeaders(headers);

  HttpResponse response = rootGetRequest.execute();
  if (response.getStatusCode() != 200) {
    throw new IOException("Unexpected return code: "
        + response.getStatusCode()
        + "\nMessage:\n"
        + response.getStatusMessage());

  }
  StringWriter writer = new StringWriter();
  IOUtils.copy(response.getContent(), writer, "UTF-8");
  String fixedString = fixProblematicPeriods(writer.toString());
  Model defaultModel = ModelFactory.createDefaultModel();
  return defaultModel.read(
      new StringReader(fixedString),
      url,
      "TURTLE");
}
 
Example 16
Source File: ControllerTest.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
@Test
void should_get_for_graphql() throws Exception {

    Thread.sleep(1000);
    final String path = basePath + config.getGraphqlConfig().port() + config.getGraphqlConfig().graphQLPath();

    final Envelope envelope = getPath(path, "text/turtle");

    final Model model = ModelFactory.createDefaultModel();
    model.read(envelope.streamBody(), "", "text/turtle");
    assertTrue(model.size() > 0);
    assertEquals(167, model.size());
}
 
Example 17
Source File: RDFToTopicMapConverter.java    From ontopia with Apache License 2.0 5 votes vote down vote up
private RDFToTopicMapConverter(String mappingurl, String syntax, TopicMapIF topicmap)
  throws JenaException, MalformedURLException {

  this.topicmap = topicmap;
  this.builder = topicmap.getBuilder();

  if (mappingurl != null) {
    Model model = ModelFactory.createDefaultModel();
    model.read(mappingurl, syntax);
    buildMappings(model);
  }
}
 
Example 18
Source File: Helpers.java    From tarql with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public static Triple triple(String tripleAsTurtle) {
	Model m = ModelFactory.createDefaultModel();
	m.read(new StringReader(tripleAsTurtle), "urn:x-base:", "TURTLE");
	return m.listStatements().next().asTriple();
}
 
Example 19
Source File: SystemTest.java    From hypergraphql with Apache License 2.0 4 votes vote down vote up
@Test
void integration_test() {

    Model mainModel = ModelFactory.createDefaultModel();
    final URL dbpediaContentUrl = getClass().getClassLoader().getResource("test_services/dbpedia.ttl");
    if(dbpediaContentUrl != null) {
        mainModel.read(dbpediaContentUrl.toString(), "TTL");
    }

    Model citiesModel = ModelFactory.createDefaultModel();
    final URL citiesContentUrl = getClass().getClassLoader().getResource("test_services/cities.ttl");
    if(citiesContentUrl != null) {
        citiesModel.read(citiesContentUrl.toString(), "TTL");
    }

    Model expectedModel = ModelFactory.createDefaultModel();
    expectedModel.add(mainModel).add(citiesModel);

    Dataset ds = DatasetFactory.createTxnMem();
    ds.setDefaultModel(citiesModel);
    FusekiServer server = FusekiServer.create()
            .add("/ds", ds)
            .build()
            .start();

    HGQLConfig externalConfig = HGQLConfig.fromClasspathConfig("test_services/externalconfig.json");

    Controller externalController = new Controller();
    externalController.start(externalConfig);

    HGQLConfig config = HGQLConfig.fromClasspathConfig("test_services/mainconfig.json");

    Controller controller = new Controller();
    controller.start(config);

    ObjectMapper mapper = new ObjectMapper();
    ObjectNode bodyParam = mapper.createObjectNode();

    bodyParam.put("query", "{\n" +
            "  Person_GET {\n" +
            "    _id\n" +
            "    label\n" +
            "    name\n" +
            "    birthPlace {\n" +
            "      _id\n" +
            "      label\n" +
            "    }\n" +
            "    \n" +
            "  }\n" +
            "  City_GET {\n" +
            "    _id\n" +
            "    label}\n" +
            "}");

    Model returnedModel = ModelFactory.createDefaultModel();

    try {
        HttpResponse<InputStream> response = Unirest.post("http://localhost:8080/graphql")
                .header("Accept", "application/rdf+xml")
                .body(bodyParam.toString())
                .asBinary();


        returnedModel.read(response.getBody(), "RDF/XML");

    } catch (UnirestException e) {
        e.printStackTrace();
    }

    Resource res = ResourceFactory.createResource("http://hypergraphql.org/query");
    Selector sel = new SelectorImpl(res, null, (Object) null);
    StmtIterator iterator = returnedModel.listStatements(sel);
    Set<Statement> statements = new HashSet<>();
    while (iterator.hasNext()) {
        statements.add(iterator.nextStatement());
    }

    for (Statement statement : statements) {
        returnedModel.remove(statement);
    }

    StmtIterator iterator2 = expectedModel.listStatements();
    while (iterator2.hasNext()) {
        assertTrue(returnedModel.contains(iterator2.next()));
    }

    assertTrue(expectedModel.isIsomorphicWith(returnedModel));
    externalController.stop();
    controller.stop();
    server.stop();
}
 
Example 20
Source File: SystemTest.java    From hypergraphql with Apache License 2.0 4 votes vote down vote up
@Test
void integration_test() {

    Model mainModel = ModelFactory.createDefaultModel();
    final URL dbpediaContentUrl = getClass().getClassLoader().getResource("test_services/dbpedia.ttl");
    if(dbpediaContentUrl != null) {
        mainModel.read(dbpediaContentUrl.toString(), "TTL");
    }

    Model citiesModel = ModelFactory.createDefaultModel();
    final URL citiesContentUrl = getClass().getClassLoader().getResource("test_services/cities.ttl");
    if(citiesContentUrl != null) {
        citiesModel.read(citiesContentUrl.toString(), "TTL");
    }

    Model expectedModel = ModelFactory.createDefaultModel();
    expectedModel.add(mainModel).add(citiesModel);

    Dataset ds = DatasetFactory.createTxnMem();
    ds.setDefaultModel(citiesModel);
    FusekiServer server = FusekiServer.create()
            .add("/ds", ds)
            .build()
            .start();



    HGQLConfig externalConfig = fromClasspathConfig("test_services/externalconfig.json");

    Controller externalController = new Controller();
    externalController.start(externalConfig);

    HGQLConfig config = fromClasspathConfig("test_services/mainconfig.json");

    Controller controller = new Controller();
    controller.start(config);

    ObjectMapper mapper = new ObjectMapper();
    ObjectNode bodyParam = mapper.createObjectNode();

    bodyParam.put("query", "{\n" +
            "  Person_GET {\n" +
            "    _id\n" +
            "    label\n" +
            "    name\n" +
            "    birthPlace {\n" +
            "      _id\n" +
            "      label\n" +
            "    }\n" +
            "    \n" +
            "  }\n" +
            "  City_GET {\n" +
            "    _id\n" +
            "    label}\n" +
            "}");

    Model returnedModel = ModelFactory.createDefaultModel();

    try {
        HttpResponse<InputStream> response = Unirest.post("http://localhost:8080/graphql")
                .header("Accept", "application/rdf+xml")
                .body(bodyParam.toString())
                .asBinary();


        returnedModel.read(response.getBody(), "RDF/XML");

    } catch (UnirestException e) {
        e.printStackTrace();
    }

    Resource res = ResourceFactory.createResource("http://hypergraphql.org/query");
    Selector sel = new SelectorImpl(res, null, (Object) null);
    StmtIterator iterator = returnedModel.listStatements(sel);
    Set<Statement> statements = new HashSet<>();
    while (iterator.hasNext()) {
        statements.add(iterator.nextStatement());
    }

    for (Statement statement : statements) {
        returnedModel.remove(statement);
    }

    StmtIterator iterator2 = expectedModel.listStatements();
    while (iterator2.hasNext()) {
        assertTrue(returnedModel.contains(iterator2.next()));
    }

    assertTrue(expectedModel.isIsomorphicWith(returnedModel));
    externalController.stop();
    controller.stop();
    server.stop();
}