Java Code Examples for com.hp.hpl.jena.rdf.model.Model#read()

The following examples show how to use com.hp.hpl.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: RdfReader.java    From EventCoreference with Apache License 2.0 6 votes vote down vote up
static void readRdfFile (String pathToRdfFile) {
        // create an empty model
        Model model = ModelFactory.createDefaultModel();

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

// read the RDF/XML file
        model.read(in, null);

// write it to standard out
        model.write(System.out);
    }
 
Example 2
Source File: ComplianceTests.java    From r2rml-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void createModelFromReified() {
	Model model = ModelFactory.createDefaultModel();
	String modelFilename = "example.rdf";
	InputStream isMap = FileManager.get().open(modelFilename);
	try {
		model.read(isMap, null, "N3");
	} catch (Exception e) {
		log.error("Error reading model.");
		System.exit(0);
	}
	
	ArrayList<Statement> stmtToAdd = new ArrayList<Statement>();
	Model newModel = ModelFactory.createDefaultModel();
	RSIterator rsIter = model.listReifiedStatements();
	while (rsIter.hasNext()) {
		ReifiedStatement rstmt = rsIter.next();
		stmtToAdd.add(rstmt.getStatement());
	}
	rsIter.close();
	newModel.add(stmtToAdd.toArray(new Statement[stmtToAdd.size()]));
	
	log.info("newModel has " + newModel.listStatements().toList().size() + " statements");
}
 
Example 3
Source File: Validator.java    From aliada-tool with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Collects the given triples sample.
 * 
 * @param jobId the job identifier.
 * @param triples the sample triples.
 */
synchronized void collectSample(final Integer jobId, final String triples) {
	if (triples == null) {
		return;
	}
	
	Model sample = samples.get(jobId);
	if (sample == null) {
		sample = ModelFactory.createDefaultModel();
		samples.put(jobId, sample);
	}
	
	try {
		sample.read(new StringReader(triples), "http://example.org", "N-TRIPLES");
	} catch (final Exception exception) {
		log.info(MessageCatalog._00059_UNABLE_TO_PARSE_SAMPLE, exception, triples);
	}
}
 
Example 4
Source File: ComplianceTests.java    From r2rml-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testSparqlQuery() {
	ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("test-context.xml");
	Util util = (Util) context.getBean("util");
	
	Model model = ModelFactory.createDefaultModel();
	String modelFilename = "dump1-epersons.rdf";
	InputStream isMap = FileManager.get().open(modelFilename);
	try {
		model.read(isMap, null, "N3");
	} catch (Exception e) {
		log.error("Error reading model.");
		System.exit(0);
	}
	String query = "SELECT ?x ?z WHERE {?x dc:source ?z} ";
	LocalResultSet rs = util.sparql(model, query);
	log.info("found " + String.valueOf(rs.getRows().size()));
	
	context.close();
}
 
Example 5
Source File: OntologyHandler.java    From dbpedia-live-mirror with GNU General Public License v3.0 6 votes vote down vote up
private List<String> getRemoteOntologyTriples() {
    List<String> triples = null;

    try (
            final ByteArrayOutputStream os = new ByteArrayOutputStream();
    ){
        Model model = ModelFactory.createDefaultModel();
        model.read(ontologyURI);

        model.write(os, "N-TRIPLE");

        String ontology = os.toString("UTF8");

        triples = new ArrayList<>();
        for (String t : ontology.split("\n")) {
            triples.add(t.trim());
        }
        Collections.sort(triples);

    } catch (Exception e) {
        logger.warn("Cannot download remote ontology", e);
    } finally {
        return triples;
    }
}
 
Example 6
Source File: LUBM.java    From neo4jena with Apache License 2.0 6 votes vote down vote up
public static void write(GraphDatabaseService njgraph) {
	Logger log= Logger.getLogger(Wine.class);
	InputStream in = FileManager.get().open( inputFileName );
	if (in == null) {
           throw new IllegalArgumentException( "File: " + inputFileName + " not found");
       }
       
	Model model = ModelFactory.createDefaultModel();
       model.read(in,"","RDF");
       double triples = model.size();
       log.info("Model loaded with " +  triples + " triples");
       System.out.println("Model loaded with " +  triples + " triples");
       
	NeoGraph graph = new NeoGraph(njgraph);
	graph.startBulkLoad();
	log.info("Connection created");
	Model njmodel = ModelFactory.createModelForGraph(graph);
	log.info("NeoGraph Model initiated");
	System.out.println("NeoGraph Model initiated");
	StopWatch watch = new StopWatch();
	//log.info(njmodel.add(model));
	njmodel.add(model);
	log.info("Storing completed (ms): " + watch.stop());
	graph.stopBulkLoad();
	System.out.println("Storing completed (ms): " + watch.stop());
}
 
Example 7
Source File: Wine.java    From neo4jena with Apache License 2.0 6 votes vote down vote up
public static void write(GraphDatabaseService njgraph) {
	InputStream in = FileManager.get().open( inputFileName );
	if (in == null) {
           throw new IllegalArgumentException( "File: " + inputFileName + " not found");
       }
       
	Model model = ModelFactory.createDefaultModel();
       model.read(in,"","RDF");
       double triples = model.size();
       System.out.println("Model loaded with " +  triples + " triples");
       
	NeoGraph graph = new NeoGraph(njgraph);
	Model njmodel = ModelFactory.createModelForGraph(graph);
	graph.startBulkLoad();
	System.out.println("NeoGraph Model initiated");
	StopWatch watch = new StopWatch();
	//log.info(njmodel.add(model));
	njmodel.add(model);
	System.out.println("Storing completed (ms): " + watch.stop());
	graph.stopBulkLoad();
}
 
Example 8
Source File: FromAndFromNamedClauses_ITCase.java    From SolRDF with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	Dataset memoryDataset = DatasetFactory.createMem();
	Model memoryModel = ModelFactory.createDefaultModel();
	memoryModel.read(new FileReader("/work/workspaces/rdf/SolRDF/solrdf/src/test/resources/sample_data/one_triple_1.ttl"), "http://e.org", "TTL");
	memoryDataset.addNamedModel("http://grapha.com", memoryModel);
	
	memoryModel = ModelFactory.createDefaultModel();
	memoryModel.read(new FileReader("/work/workspaces/rdf/SolRDF/solrdf/src/test/resources/sample_data/one_triple_2.ttl"), "http://e.org", "TTL");
	memoryDataset.addNamedModel("http://graphb.com", memoryModel);
	
	memoryModel = ModelFactory.createDefaultModel();
	memoryModel.read(new FileReader("/work/workspaces/rdf/SolRDF/solrdf/src/test/resources/sample_data/one_triple_3.ttl"), "http://e.org", "TTL");
	memoryDataset.addNamedModel("http://graphc.com", memoryModel);
	
	memoryModel = ModelFactory.createDefaultModel();
	memoryModel.read(new FileReader("/work/workspaces/rdf/SolRDF/solrdf/src/test/resources/sample_data/one_triple_4.ttl"), "http://e.org", "TTL");
	memoryDataset.addNamedModel("http://graphd.com", memoryModel);
	
	final Query query = QueryFactory.create(q2());//"SELECT ?s FROM <http://grapha.com> WHERE { ?s <http://example.org/title> ?o }");
	
	System.out.println(ResultSetFormatter.asText(QueryExecutionFactory.create(query, memoryDataset).execSelect()));
}
 
Example 9
Source File: Course.java    From neo4jena with Apache License 2.0 5 votes vote down vote up
public static void write(GraphDatabaseService njgraph) {
	InputStream in = FileManager.get().open( inputFileName );
	if (in == null) {
           throw new IllegalArgumentException( "File: " + inputFileName + " not found");
       }
       
	Model model = ModelFactory.createDefaultModel();
       model.read(in,"","TTL");
       double triples = model.size();
       log.info("Model loaded with " +  triples + " triples");
       System.out.println("Model loaded with " +  triples + " triples");
       Map<String, String> prefixMap = model.getNsPrefixMap();
      // System.out.println("Prefix Mapping: " + prefixMap);
       
	NeoGraph graph = new NeoGraph(njgraph);
	graph.getPrefixMapping().setNsPrefixes(prefixMap);
	graph.startBulkLoad();
	log.info("Connection created");
	Model njmodel = ModelFactory.createModelForGraph(graph);
	log.info("NeoGraph Model initiated");
	System.out.println("NeoGraph Model initiated");
	
	//log.info(njmodel.add(model));
	//njmodel.add(model);
	StmtIterator iterator = model.listStatements();
	StopWatch watch = new StopWatch();
	int count = 0;
	while(iterator.hasNext()){
		njmodel.add(iterator.next());
		count++;
	}
	System.out.println("Total triples loaded are:"+ count);
	graph.stopBulkLoad();
	//log.info("Storing completed (ms): " + watch.stop());
	System.out.println("Storing completed (ms): " + watch.stop());
}
 
Example 10
Source File: SimpleRDFJsonLDImport.java    From wandora with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void importRDF(InputStream in, TopicMap map) {
    if(in != null) {
        // create an empty model
        Model model = ModelFactory.createDefaultModel();
        // read the RDF json-ld file
        model.read(in, "", "JSON-LD");
        RDF2TopicMap(model, map);
    }
}
 
Example 11
Source File: BasicRDFJsonLDImport.java    From wandora with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void importRDF(InputStream in, TopicMap map) {
    if(in != null) {
        // create an empty model
        Model model = ModelFactory.createDefaultModel();
        // read the RDF json-ld file
        model.read(in, "", "JSON-LD");
        RDF2TopicMap(model, map);
    }
}
 
Example 12
Source File: Course_Test.java    From neo4jena with Apache License 2.0 5 votes vote down vote up
public static void write(BatchInserter inserter) {
	InputStream in = FileManager.get().open( inputFileName );
	if (in == null) {
           throw new IllegalArgumentException( "File: " + inputFileName + " not found");
       }
       
	Model model = ModelFactory.createDefaultModel();

	StopWatch watch = new StopWatch();
       BatchHandler handler = new BatchHandler(inserter,500000,60);
       model.register(handler);
       
       model.read(in,"","TTL");	

       double triples = model.size();
       //log.info("Model loaded with " +  triples + " triples");
       System.out.println("Model loaded with " +  triples + " triples" + " time taken: " + watch.stop());
       //Map<String, String> prefixMap = model.getNsPrefixMap();
      // System.out.println("Prefix Mapping: " + prefixMap);
       
	//NeoGraph graph = new NeoGraph(njgraph);
	//graph.getPrefixMapping().setNsPrefixes(prefixMap);
	//graph.startBulkLoad();
	//log.info("Connection created");
	//Model njmodel = ModelFactory.createModelForGraph(graph);
	/*log.info("NeoGraph Model initiated");
	System.out.println("NeoGraph Model initiated");
	
	StopWatch watch = new StopWatch();
	//njmodel.add(model);
	
	long endTime = watch.stop();
	
	log.info("Total triples loaded are:"+ graph.size());
	System.out.println("Total triples loaded are:"+ graph.size());
	graph.stopBulkLoad();
	
	log.info("Storing completed (ms): " + endTime);
	System.out.println("Storing completed (ms): " + endTime);*/
}
 
Example 13
Source File: ToN3.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * @param args ..
 */
public static void main(String[] args) throws FileNotFoundException {
	Model m = ModelFactory.createDefaultModel();
	m.read(new FileInputStream(new File(
	        "P:\\__sirdf\\rdf2go\\src\\org\\ontoware\\rdf2go\\example\\thiemann.foaf.rdf.xml")),
	        "");
	m.write(System.out, "N-TRIPLES");
}
 
Example 14
Source File: MetadataCreator.java    From GeoTriples with Apache License 2.0 5 votes vote down vote up
public static Model loadMetadataTemplate(InputStream is) {
	try {
		Model tplModel = ModelFactory.createDefaultModel();
		tplModel.read(is, "about:prefix:", "TTL");
		return tplModel;
	} catch (JenaException e) {
		// ignore
	}
	return null;
}
 
Example 15
Source File: IntegrationTestSupertypeLayer.java    From SolRDF with Apache License 2.0 4 votes vote down vote up
/**
 * Loads all triples found in the datafile associated with the given name.
 * 
 * @param datafileName the name of the datafile.
 * @param graphs an optional set of target graph URIs. 
 * @throws Exception hopefully never, otherwise the test fails.
 */
protected void load(final MisteryGuest data) throws Exception {
	if (data.datasets == null || data.datasets.length == 0) {
		return;
	}
	
	final Model memoryModel = data.graphURI != null 
			? memoryDataset.getNamedModel(data.graphURI) 
			: memoryDataset.getDefaultModel();
			 
	for (final String datafileName : data.datasets) {
		final String dataURL = source(datafileName).toString();
		final String lang = datafileName.endsWith("ttl") 
				? "TTL" 
				: datafileName.endsWith("nt") 
					? "N-TRIPLES" 
					: null;
		memoryModel.read(dataURL, DUMMY_BASE_URI, lang);
	}  
 
	if (data.graphURI != null) {
		SOLRDF_CLIENT.add(data.graphURI, memoryModel.listStatements());
	} else {
		SOLRDF_CLIENT.add(memoryModel.listStatements());
	}
	
	SOLRDF_CLIENT.commit();
	
	final Iterator<Node> nodes = memoryDataset.asDatasetGraph().listGraphNodes();
	if (nodes != null) {
		while (nodes.hasNext()) {
			final Node graphNode = nodes.next();
			final String graphUri = graphNode.getURI();
			final Model inMemoryNamedModel = memoryDataset.getNamedModel(graphUri);
			assertIsomorphic(inMemoryNamedModel, SOLRDF_CLIENT.getNamedModel(graphUri), graphUri);		
		}
	}
	
	final Model model = (data.graphURI != null) ? SOLRDF_CLIENT.getNamedModel(data.graphURI) : SOLRDF_CLIENT.getDefaultModel();
	assertFalse(Arrays.toString(data.datasets) + ", " + data.query, model.isEmpty());
	assertIsomorphic(memoryModel, model, null);
}
 
Example 16
Source File: RDFConfig.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
public Model createRDFModel() throws IOException, DataServiceFault {
	InputStream in = DBUtils.getInputStreamFromPath(this.getRDFDataSourcePath());
	Model model = ModelFactory.createMemModelMaker().createDefaultModel();
	model.read(in,null);		
	return model;
}
 
Example 17
Source File: ValidationClient.java    From aliada-tool with GNU General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) throws FileNotFoundException {
	Model model = ModelFactory.createDefaultModel();
	model.read(new FileReader("???"), "http://example,org", "N3");
	
	System.out.println(model.size());
}
 
Example 18
Source File: ResourceBuilder.java    From LodView with MIT License 4 votes vote down vote up
public ResultBean buildHtmlResource(String IRI, Locale locale, ConfigurationBean conf, OntologyBean ontoBean, boolean localMode) throws Exception {
	ResultBean result = new ResultBean();
	List<String> videos = new ArrayList<String>();
	List<String> audios = new ArrayList<String>();
	List<String> images = new ArrayList<String>();
	List<String> linking = new ArrayList<String>();
	SPARQLEndPoint se = new SPARQLEndPoint(conf, ontoBean, locale.getLanguage());
	result.setMainIRI(IRI);

	String preferredLanguage = conf.getPreferredLanguage();
	if (preferredLanguage.equals("auto")) {
		preferredLanguage = locale.getLanguage();
	}
	List<TripleBean> triples = new ArrayList<TripleBean>();
	if (conf.getEndPointUrl() != null && conf.getEndPointUrl().equals("<>")) {
		localMode = true;
	}
	if (localMode) {
		/* looking for data via content negotiation */
		Model m = ModelFactory.createDefaultModel();
		try {
			m.read(IRI);
		} catch (Exception e) {
			throw new Exception(messageSource.getMessage("error.noContentNegotiation", null, "sorry but content negotiation is not supported by the IRI", locale));
		}
		triples = se.doLocalQuery(m, IRI, conf.getDefaultQueries());
	} else {
		triples = se.doQuery(IRI, conf.getDefaultQueries(), null);
	}
	boolean betterTitleMatch = false, betterDescrMatch = false;
	for (TripleBean tripleBean : triples) {

		if (tripleBean.getIRI() == null) {
			tripleBean.setIRI(IRI);
			tripleBean.setNsIRI(Misc.toNsResource(tripleBean.getIRI(), conf));
		}

		if (conf.getTitleProperties().contains(tripleBean.getProperty().getNsProperty()) || conf.getTitleProperties().contains(tripleBean.getProperty().getProperty())) {
			if (tripleBean.getIRI().equals(IRI) && !betterTitleMatch && (result.getTitle() == null || result.getTitle().trim().equals("") || (tripleBean.getLang() != null && (preferredLanguage.equals(tripleBean.getLang()) || tripleBean.getLang().equals("en"))))) {
				result.setTitle(Misc.stripHTML(tripleBean.getValue()));
				if (preferredLanguage.equals(tripleBean.getLang())) {
					betterTitleMatch = true;
				}
			}
		} else if (conf.getDescriptionProperties().contains(tripleBean.getProperty().getNsProperty()) || conf.getDescriptionProperties().contains(tripleBean.getProperty().getProperty())) {
			if (tripleBean.getIRI().equals(IRI) && !betterDescrMatch && (result.getDescriptionProperty() == null || (tripleBean.getLang() != null && (preferredLanguage.equals(tripleBean.getLang()) || tripleBean.getLang().equals("en"))))) {
				result.setDescriptionProperty(tripleBean.getProperty());
				if (preferredLanguage.equals(tripleBean.getLang())) {
					betterDescrMatch = true;
				}
			}
		} else if (conf.getLatitudeProperties().contains(tripleBean.getProperty().getNsProperty()) || conf.getLatitudeProperties().contains(tripleBean.getProperty().getProperty())) {
			result.setLatitude(tripleBean.getValue());
		} else if (conf.getLongitudeProperties().contains(tripleBean.getProperty().getNsProperty()) || conf.getLongitudeProperties().contains(tripleBean.getProperty().getProperty())) {
			result.setLongitude(tripleBean.getValue());
		} else if (conf.getImageProperties().contains(tripleBean.getProperty().getNsProperty()) || conf.getImageProperties().contains(tripleBean.getProperty().getProperty())) {
			images.add(tripleBean.getValue());
		}  else if (conf.getAudioProperties().contains(tripleBean.getProperty().getNsProperty()) || conf.getAudioProperties().contains(tripleBean.getProperty().getProperty())) {
			audios.add(tripleBean.getValue());
		} else if (conf.getVideoProperties().contains(tripleBean.getProperty().getNsProperty()) || conf.getVideoProperties().contains(tripleBean.getProperty().getProperty())) {
			videos.add(tripleBean.getValue());
		}  else if (conf.getLinkingProperties().contains(tripleBean.getProperty().getNsProperty()) || conf.getLinkingProperties().contains(tripleBean.getProperty().getProperty())) {
			linking.add(tripleBean.getValue());
		} else if (conf.getTypeProperties().contains(tripleBean.getProperty().getNsProperty()) || conf.getTypeProperties().contains(tripleBean.getProperty().getProperty())) {
			result.setTypeProperty(tripleBean.getProperty());
		}

		if (tripleBean.getType().equals("iri")) {
			tripleBean.setUrl(Misc.toBrowsableUrl(tripleBean.getValue(), conf));
			tripleBean.setNsValue(Misc.toNsResource(tripleBean.getValue(), conf));
			if (!tripleBean.getUrl().equals(tripleBean.getValue()) || tripleBean.getValue().startsWith(conf.getPublicUrlPrefix())) {
				tripleBean.setLocal(true);
			}
			result.addResource(tripleBean, tripleBean.getIRI());
		} else if (tripleBean.getType().equals("literal")) {
			result.addLiteral(tripleBean, tripleBean.getIRI());
		} else if (tripleBean.getType().equals("bnode")) {
			result.addBnode(tripleBean, tripleBean.getIRI());
		}
	}

	result.setImages(images);
	result.setLinking(linking);
	result.setVideos(videos);
	result.setAudios(audios);

	return result;
}