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

The following examples show how to use org.apache.jena.rdf.model.Model#write() . 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: EarlReporter.java    From teamengine with Apache License 2.0 6 votes vote down vote up
/**
 * Writes the model to a file (earl-results.rdf) in the specified directory
 * using the RDF/XML syntax.
 * 
 * @param model
 *            A representation of an RDF graph.
 * @param outputDirectory
 *            A File object denoting the directory in which the results file
 *            will be written.
 * @param abbreviated
 *            Indicates whether or not to serialize the model using the
 *            abbreviated syntax.
 * @throws IOException
 *             If an IO error occurred while trying to serialize the model
 *             to a (new) file in the output directory.
 */
void writeModel(Model model, File outputDirectory, boolean abbreviated) throws IOException {
    if (!outputDirectory.isDirectory()) {
        throw new IllegalArgumentException(
                "Directory does not exist at " + outputDirectory.getAbsolutePath());
    }
    File outputFile = new File(outputDirectory, "earl-results.rdf");
    if (!outputFile.createNewFile()) {
        outputFile.delete();
        outputFile.createNewFile();
    }
    LOGR.log(Level.CONFIG, "Writing EARL results to" + outputFile.getAbsolutePath());
    String syntax = (abbreviated) ? "RDF/XML-ABBREV" : "RDF/XML";
    String baseUri = new StringBuilder("http://example.org/earl/")
            .append(outputDirectory.getName()).append('/').toString();
    OutputStream outStream = new FileOutputStream(outputFile);
    try (Writer writer = new OutputStreamWriter(outStream, StandardCharsets.UTF_8)) {
        model.write(writer, syntax, baseUri);
    }
}
 
Example 2
Source File: ExRIOT_out1.java    From xcurator with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args)
{
    Model model = RDFDataMgr.loadModel("D.ttl") ;
    
    System.out.println() ;
    System.out.println("#### ---- Write as Turtle") ;
    System.out.println() ;
    RDFDataMgr.write(System.out, model, Lang.TURTLE) ;
    
    System.out.println() ;
    System.out.println("#### ---- Write as Turtle (streaming)") ;
    System.out.println() ;
    RDFDataMgr.write(System.out, model, RDFFormat.TURTLE_BLOCKS) ;
    
    System.out.println() ;
    System.out.println("#### ---- Write as Turtle via model.write") ;
    System.out.println() ;
    model.write(System.out, "TTL") ;
}
 
Example 3
Source File: SolidUtilities.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
/** Posts an RDF model to a Solid server. **/
public String postContent(
    String url,
    String slug,
    String type,
    Model model)
    throws IOException {
  StringWriter stringWriter = new StringWriter();
  model.write(stringWriter, "TURTLE");
  HttpContent content = new ByteArrayContent("text/turtle", stringWriter.toString().getBytes());

  HttpRequest postRequest = factory.buildPostRequest(
      new GenericUrl(url), content);
  HttpHeaders headers = new HttpHeaders();
  headers.setCookie(authCookie);
  headers.set("Link", "<" + type + ">; rel=\"type\"");
  headers.set("Slug", slug);
  postRequest.setHeaders(headers);

  HttpResponse response = postRequest.execute();

  validateResponse(response, 201);
  return response.getHeaders().getLocation();
}
 
Example 4
Source File: OCUtils.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
public static OWLOntology load(Model tbox) throws IOException, OWLOntologyCreationException{
	File tempFile = File.createTempFile("tboxmodel", ".ttl");
	FileOutputStream out = new FileOutputStream(tempFile);
	tbox.write(out);
	out.flush();
	out.close();
	return load(tempFile);
}
 
Example 5
Source File: TarqlTest.java    From tarql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void assertConstruct(TarqlQuery tq, String expectedTTL) throws IOException {
	Model expected = ModelFactory.createDefaultModel().read(new StringReader(expectedTTL), null, "TURTLE");
	TarqlQueryExecution ex = TarqlQueryExecutionFactory.create(tq, InputStreamSource.fromBytes(csv.getBytes("utf-8")), options);
	Model actual = ModelFactory.createDefaultModel();
	ex.exec(actual);
	if (!actual.isIsomorphicWith(expected)) {
		StringWriter out = new StringWriter();
		actual.write(out, "TURTLE");
		fail("Actual not isomorphic to input. Actual was:\n" + out.toString());
	}
}
 
Example 6
Source File: RdfFileWriter.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
@Override
public void write(QueryExecutionFactory qef) throws RdfWriterException {

    File file = new File(filename);
    if (file.exists() && skipIfExists) {
        return;
    }

    if (file.exists() && !overwrite) {
        throw new RdfWriterException("Error writing file: File already exists and cannot overwrite");
    }


    if (createParentDirectories) {
        File parentF = file.getParentFile();
        if (parentF != null && !parentF.exists() && !parentF.mkdirs()) {
            throw new RdfWriterException("Error writing file: Cannot create new directory structure for file: " + filename);
        }
    }

    try (OutputStream fos = new FileOutputStream(file)) {

        Model model = IOUtils.getModelFromQueryFactory(qef);
        PrefixNSService.setNSPrefixesInModel(model);
        model.write(fos, filetype);

    } catch (Exception e) {
        throw new RdfWriterException("Error writing file: " + e.getMessage(), e);
    }

}
 
Example 7
Source File: RdfStreamWriter.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
@Override
public void write(QueryExecutionFactory qef) throws RdfWriterException {
    try {
        Model model = IOUtils.getModelFromQueryFactory(qef);
        PrefixNSService.setNSPrefixesInModel(model);
        model.write(outputStream, filetype);

    } catch (Exception e) {
        throw new RdfWriterException("Error writing in OutputStream: " + e.getMessage(), e);
    }
}
 
Example 8
Source File: CtlEarlReporter.java    From teamengine with Apache License 2.0 5 votes vote down vote up
private void writeModel( Model earlModel, OutputStream outStream, boolean abbreviated, String baseUri )
                        throws IOException {
    String syntax = ( abbreviated ) ? "RDF/XML-ABBREV" : "RDF/XML";
    try (Writer writer = new OutputStreamWriter( outStream, StandardCharsets.UTF_8 )) {
        earlModel.write( writer, syntax, baseUri );
    }
}
 
Example 9
Source File: ExRIOT_out3.java    From xcurator with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args)
{
    System.out.println("## Example of a registering a new language with RIOT") ; 
    System.out.println() ;
    
    // Register the language
    Lang lang = LangBuilder.create("SSE", "text/x-sse").addFileExtensions("rsse").build() ;
    RDFLanguages.register(lang) ;

    // Create format and register the association of language and default format.
    // We are creating only one format here but in geenral theer can be variants
    // (e.g. TURTLE - pretty printed or streamed) 
    RDFFormat format = new RDFFormat(lang) ;
    RDFWriterRegistry.register(lang, format)  ;
    
    // Register the writer factory
    RDFWriterRegistry.register(format, new SSEWriterFactory()) ;

    // ---- Use the register writer
    Model model = RDFDataMgr.loadModel("/home/afs/tmp/D.ttl") ;
    // Write
    System.out.println("## Write by format") ;
    RDFDataMgr.write(System.out, model, format) ;
    System.out.println() ;
    System.out.println("## Write by language") ;
    RDFDataMgr.write(System.out, model, lang) ;
    
    // ---- Or use Model.write
    System.out.println("## Write by Model.write") ;
    model.write(System.out, "SSE") ;
}
 
Example 10
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 11
Source File: Infer.java    From shacl with Apache License 2.0 5 votes vote down vote up
private void run(String[] args) throws IOException {
	Model dataModel = getDataModel(args);
	Model shapesModel = getShapesModel(args);
	if(shapesModel == null) {
		shapesModel = dataModel;
	}
	Model results = RuleUtil.executeRules(dataModel, shapesModel, null, null);
	results.write(System.out, FileUtils.langTurtle);
}
 
Example 12
Source File: Utils.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 *   Device정보 리턴
 * @param deviceUri
 * @return String
 * @throws Exception
 */
public static String getDeviceInfo(String deviceUri) throws Exception {
	String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.dw.sparql.endpoint")+"/sparql";
	StringWriter out = new StringWriter();
	String query = getSparQlHeader() + "\n"+ "describe "+ deviceUri;

	QueryExecution qe = QueryExecutionFactory.sparqlService(serviceURI, query);
	Model model =   qe.execDescribe();
	qe.close();
	model.write(out,"RDF/XML");
	return out.toString();
}
 
Example 13
Source File: PropertySurfaceForms.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 {

		PROPERTY_SURFACE_FORMS = DIRECTORY + "property_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_PROPERTY_FILE);
		if (in == null) {
			throw new IllegalArgumentException("File: " + DBPEDIA_PROPERTY_FILE + " not found");
		}

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

		Model outputModel = ModelFactory.createDefaultModel();
		QueryExecution qExec = QueryExecutionFactory
				.create("SELECT ?s  ?label WHERE{?s a <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property>."
						+ " ?s <http://www.w3.org/2000/01/rdf-schema#label> ?label. }", inputModel);
		ResultSet rs = qExec.execSelect();
		System.out.println(qExec);
		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(PROPERTY_SURFACE_FORMS);
		RDFDataMgr.write(outputFile, outputModel, RDFFormat.NTRIPLES);
	}
 
Example 14
Source File: Utils.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 *   Device정보 리턴
 * @param deviceUri
 * @return String
 * @throws Exception
 */
public static String getDeviceInfo(String deviceUri) throws Exception {
	String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.dw.sparql.endpoint")+"/sparql";
	StringWriter out = new StringWriter();
	String query = getSparQlHeader() + "\n"+ "describe "+ deviceUri;

	QueryExecution qe = QueryExecutionFactory.sparqlService(serviceURI, query);
	Model model =   qe.execDescribe();
	qe.close();
	model.write(out,"RDF/XML");
	return out.toString();
}
 
Example 15
Source File: RoundTripToRdfTest.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
@Test
public void testFromVcard() {
  for (VCard vcardInput : Ezvcard.parse(TestData.VCARD_TEXT).all()) {
    Model personModel = SolidContactsImport.getPersonModel(vcardInput);

    StringWriter stringWriter = new StringWriter();
    personModel.write(stringWriter, "TURTLE");
    String rdf = stringWriter.toString();

    VCard vcardOutput = SolidContactsExport.parsePerson(getPersonResource(rdf));
    checkEquality(vcardInput, vcardOutput);
  }
}
 
Example 16
Source File: OCUtils.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
public static void convertToNtripleFormat(File in, File out) throws IOException {
	Model model = FileManager.get().loadModel(in.getAbsolutePath());
	BufferedWriter bw = new BufferedWriter(new FileWriter(out));
	model.write(bw, "N-TRIPLE");
	bw.close();
}
 
Example 17
Source File: TestBaseGenerate.java    From sparql-generate with Apache License 2.0 4 votes vote down vote up
@Test
    public void testPlanExecution() throws Exception {

        String query = IOUtils.toString(sm.open(new LookUpRequest(request.query, SPARQLExt.MEDIA_TYPE)), "UTF-8");

        long start0 = System.currentTimeMillis();
        long start = start0;
        SPARQLExtQuery q = (SPARQLExtQuery) QueryFactory.create(query, SPARQLExt.SYNTAX);
        long now = System.currentTimeMillis();
        log.info("needed " + (now - start) + " to parse query");
        start = now;

        // create generation plan
        RootPlan plan = PlanFactory.create(q);
        Dataset ds = request.loadDataset(exampleDir);

        now = System.currentTimeMillis();
        log.info("needed " + (now - start) + " to get ready");
        start = now;

        // execute plan

        ExecutorService executor = new ForkJoinPool(Runtime.getRuntime().availableProcessors(),
            (ForkJoinPool pool) -> {
                final ForkJoinWorkerThread worker = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);
                worker.setName("test-" + name + "-" + worker.getPoolIndex());
                return worker;
            },
            null, true);

        ScheduledExecutorService guard = Executors.newScheduledThreadPool(1);
        guard.schedule(()->{executor.shutdownNow();}, 15, TimeUnit.SECONDS);
        Model output;
        Context context = ContextUtils.build()
                .setPrefixMapping(q)
                .setStreamManager(sm)
                .setExecutor(executor)
                .setInputDataset(ds)
                .build();
        output = plan.execGenerate(context);
        guard.shutdownNow();

        now = System.currentTimeMillis();
        log.info("executed plan in " + (now - start));
        start = now;
        log.info("total needed " + (now - start0));

        // write output
        String fileName = exampleDir.toString() + "/output.ttl";
        FileWriter out = new FileWriter(fileName);
        try {
            output.write(out, "TTL");
            StringWriter sw = new StringWriter();
            output.write(sw, "TTL");
            LOG.debug("output is \n" + sw.toString());
        } finally {
            try {
                out.close();
            } catch (IOException closeException) {
                log.error("Error while writing to file");
            }
        }

        URI expectedOutputUri = exampleDir.toURI().resolve("expected_output.ttl");
        Model expectedOutput = RDFDataMgr.loadModel(expectedOutputUri.toString(), Lang.TTL);
//        StringWriter sw = new StringWriter();
//        expectedOutput.write(System.out, "TTL");
        System.out.println("Is isomorphic: " + output.isIsomorphicWith(expectedOutput));
        if (!output.isIsomorphicWith(expectedOutput)) {
            output.listStatements().forEachRemaining((s) -> {
                if (!expectedOutput.contains(s)) {
                    LOG.debug("expectedOutput does not contain " + s);
                }
                expectedOutput.remove(s);
            });
            expectedOutput.listStatements().forEachRemaining((s) -> {
                LOG.debug("output does not contain " + s);
            });
        }

        assertTrue("Error with test " + exampleDir.getName(), output.isIsomorphicWith(expectedOutput));
    }
 
Example 18
Source File: Importer.java    From fcrepo-import-export with Apache License 2.0 4 votes vote down vote up
private InputStream modelToStream(final Model model) {
    final ByteArrayOutputStream buf = new ByteArrayOutputStream();
    model.write(buf, config.getRdfLanguage());
    return new ByteArrayInputStream(buf.toByteArray());
}