com.hp.hpl.jena.rdf.model.ModelFactory Java Examples

The following examples show how to use com.hp.hpl.jena.rdf.model.ModelFactory. 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: DataTypeTesting.java    From semweb4j with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testNewToJenaNode() throws ModelRuntimeException {
	com.hp.hpl.jena.rdf.model.Model model = ModelFactory.createDefaultModel();
	
	DatatypeLiteralImpl l1 = new DatatypeLiteralImpl("test", new URIImpl("test:funky", false));
	DatatypeLiteralImpl l2 = new DatatypeLiteralImpl("test", new URIImpl("test:funky", false));
	
	Node n1 = TypeConversion.toJenaNode(l1, model);
	Node n2 = TypeConversion.toJenaNode(l2, model);
	
	assertTrue(n1.equals(n2));
	
	Object o1 = TypeConversion.toRDF2Go(n1);
	Object o2 = TypeConversion.toRDF2Go(n2);
	
	assertTrue(o1 instanceof DatatypeLiteral);
	assertTrue(o2 instanceof DatatypeLiteral);
	
	DatatypeLiteralImpl new1 = (DatatypeLiteralImpl)o1;
	DatatypeLiteralImpl new2 = (DatatypeLiteralImpl)o2;
	
	assertTrue(new1.getValue().equals("test"));
	assertTrue(new2.getValue().equals("test"));
	assertTrue(new1.getDatatype().equals(new URIImpl("test:funky", false)));
	assertTrue(new2.getDatatype().equals(new URIImpl("test:funky", false)));
}
 
Example #2
Source File: ResourceBuilder.java    From LodView with MIT License 6 votes vote down vote up
public String buildRDFResource(String IRI, String sparql, Lang lang, ConfigurationBean conf) throws Exception {
	String result = "empty content";
	Model model = ModelFactory.createDefaultModel();
	model.setNsPrefixes(conf.getPrefixes());

	SPARQLEndPoint se = new SPARQLEndPoint(conf, null, null);
	model = se.extractData(model, IRI, sparql, conf.getDefaultRawDataQueries());

	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	RDFWriter rdfWriter = model.getWriter(lang.getName());
	rdfWriter.setProperty("showXMLDeclaration","true");
	rdfWriter.setProperty("relativeURIs","");

	rdfWriter.write(model, baos, conf.getIRInamespace());

	byte[] resultByteArray = baos.toByteArray();
	result = new String(resultByteArray);

	return result;
}
 
Example #3
Source File: CSPARQLAarhusWeatherStream.java    From Benchmark with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected List<Statement> getStatements(SensorObservation wo) throws NumberFormatException, IOException {
	Model m = ModelFactory.createDefaultModel();
	if (ed != null)
		for (String s : ed.getPayloads()) {
			Resource observation = m
					.createResource(RDFFileManager.defaultPrefix + wo.getObId() + UUID.randomUUID());
			// wo.setObId(observation.toString());
			CityBench.obMap.put(observation.toString(), wo);
			observation.addProperty(RDF.type, m.createResource(RDFFileManager.ssnPrefix + "Observation"));
			Resource serviceID = m.createResource(ed.getServiceId());
			observation.addProperty(m.createProperty(RDFFileManager.ssnPrefix + "observedBy"), serviceID);
			observation.addProperty(m.createProperty(RDFFileManager.ssnPrefix + "observedProperty"),
					m.createResource(s.split("\\|")[2]));
			Property hasValue = m.createProperty(RDFFileManager.saoPrefix + "hasValue");
			if (s.contains("Temperature"))
				observation.addLiteral(hasValue, ((WeatherObservation) wo).getTemperature());
			else if (s.toString().contains("Humidity"))
				observation.addLiteral(hasValue, ((WeatherObservation) wo).getHumidity());
			else if (s.toString().contains("WindSpeed"))
				observation.addLiteral(hasValue, ((WeatherObservation) wo).getWindSpeed());
		}
	return m.listStatements().toList();
}
 
Example #4
Source File: ResourceBuilder.java    From LodView with MIT License 6 votes vote down vote up
public String buildRDFResource(String IRI, Model m, Lang lang, ConfigurationBean conf) throws Exception {
	String result = "empty content";
	Model model = ModelFactory.createDefaultModel();
	model.setNsPrefixes(conf.getPrefixes());

	SPARQLEndPoint se = new SPARQLEndPoint(conf, null, null);
	model = se.extractLocalData(model, IRI, m, conf.getDefaultRawDataQueries());

	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	RDFWriter rdfWriter = model.getWriter(lang.getName());
	rdfWriter.setProperty("showXMLDeclaration","true");
	rdfWriter.setProperty("relativeURIs","");

	rdfWriter.write(model, baos, conf.getIRInamespace());
	rdfWriter.setProperty("showXMLDeclaration","true");
	rdfWriter.setProperty("relativeURIs","");

	byte[] resultByteArray = baos.toByteArray();
	result = new String(resultByteArray);

	return result;
}
 
Example #5
Source File: CSPARQLAarhusParkingStream.java    From Benchmark with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected List<Statement> getStatements(SensorObservation so) throws NumberFormatException, IOException {
	Model m = ModelFactory.createDefaultModel();
	Resource observation = m.createResource(RDFFileManager.defaultPrefix + so.getObId() + UUID.randomUUID());
	CityBench.obMap.put(observation.toString(), so);
	observation.addProperty(RDF.type, m.createResource(RDFFileManager.ssnPrefix + "Observation"));
	// observation.addProperty(RDF.type,
	// m.createResource(RDFFileManager.saoPrefix + "StreamData"));
	Resource serviceID = m.createResource(ed.getServiceId());
	observation.addProperty(m.createProperty(RDFFileManager.ssnPrefix + "observedBy"), serviceID);
	// Resource property = m.createResource(s.split("\\|")[2]);
	// property.addProperty(RDF.type, m.createResource(s.split("\\|")[0]));
	observation.addProperty(m.createProperty(RDFFileManager.ssnPrefix + "observedProperty"),
			m.createResource(ed.getPayloads().get(0).split("\\|")[2]));
	Property hasValue = m.createProperty(RDFFileManager.saoPrefix + "hasValue");
	// Literal l;
	// System.out.println("Annotating: " + observedProperty.toString());
	// if (observedProperty.contains("AvgSpeed"))
	observation.addLiteral(hasValue, ((AarhusParkingObservation) so).getVacancies());
	// observation.addLiteral(m.createProperty(RDFFileManager.ssnPrefix + "featureOfInterest"),
	// ((AarhusParkingObservation) so).getGarageCode());
	return m.listStatements().toList();
}
 
Example #6
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 #7
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 #8
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 #9
Source File: AutoReloadableDataset.java    From GeoTriples with Apache License 2.0 6 votes vote down vote up
private void reload() {
	loader.getMapping().connect();
	Graph graph = loader.getGraphD2RQ();
	
	datasetGraph = DatasetGraphFactory.createOneGraph(graph);
	defaultModel = ModelFactory.createModelForGraph(datasetGraph.getDefaultGraph());		

	hasTruncatedResults = false;
	for (SQLConnection db: loader.getMapping().getSQLConnections()) {
		if (db.limit() != Database.NO_LIMIT) {
			hasTruncatedResults = true;
		}
	}

	if (autoReload) {
		lastModified = watchedFile.lastModified();
		lastReload = System.currentTimeMillis();
	}
}
 
Example #10
Source File: CSPARQLAarhusPollutionStream.java    From Benchmark with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected List<Statement> getStatements(SensorObservation so) {
	Model m = ModelFactory.createDefaultModel();
	if (ed != null)
		for (String s : ed.getPayloads()) {
			Resource observation = m
					.createResource(RDFFileManager.defaultPrefix + so.getObId() + UUID.randomUUID());
			// so.setObId(RDFFileManager.defaultPrefix + observation.toString());
			CityBench.obMap.put(observation.toString(), so);
			observation.addProperty(RDF.type, m.createResource(RDFFileManager.ssnPrefix + "Observation"));

			Resource serviceID = m.createResource(ed.getServiceId());
			observation.addProperty(m.createProperty(RDFFileManager.ssnPrefix + "observedBy"), serviceID);
			observation.addProperty(m.createProperty(RDFFileManager.ssnPrefix + "observedProperty"),
					m.createResource(s.split("\\|")[2]));
			Property hasValue = m.createProperty(RDFFileManager.saoPrefix + "hasValue");
			observation.addLiteral(hasValue, ((PollutionObservation) so).getApi());
		}
	return m.listStatements().toList();
}
 
Example #11
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 #12
Source File: DataWrapper.java    From Benchmark with GNU General Public License v3.0 6 votes vote down vote up
public static List<Statement> getAarhusWeatherStatements(SensorObservation wo, EventDeclaration ed) {
	Model m = ModelFactory.createDefaultModel();
	if (ed != null)
		for (String s : ed.getPayloads()) {
			Resource observation = m
					.createResource(RDFFileManager.defaultPrefix + wo.getObId() + UUID.randomUUID());
			// wo.setObId(observation.toString());
			CityBench.obMap.put(observation.toString(), wo);
			observation.addProperty(RDF.type, m.createResource(RDFFileManager.ssnPrefix + "Observation"));
			Resource serviceID = m.createResource(ed.getServiceId());
			observation.addProperty(m.createProperty(RDFFileManager.ssnPrefix + "observedBy"), serviceID);
			observation.addProperty(m.createProperty(RDFFileManager.ssnPrefix + "observedProperty"),
					m.createResource(s.split("\\|")[2]));
			Property hasValue = m.createProperty(RDFFileManager.saoPrefix + "hasValue");
			if (s.contains("Temperature"))
				observation.addLiteral(hasValue, ((WeatherObservation) wo).getTemperature());
			else if (s.toString().contains("Humidity"))
				observation.addLiteral(hasValue, ((WeatherObservation) wo).getHumidity());
			else if (s.toString().contains("WindSpeed"))
				observation.addLiteral(hasValue, ((WeatherObservation) wo).getWindSpeed());
		}
	return m.listStatements().toList();
}
 
Example #13
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 #14
Source File: DataWrapper.java    From Benchmark with GNU General Public License v3.0 6 votes vote down vote up
public static List<Statement> getAarhusParkingStatements(SensorObservation so, EventDeclaration ed) {
	Model m = ModelFactory.createDefaultModel();
	Resource observation = m.createResource(RDFFileManager.defaultPrefix + so.getObId() + UUID.randomUUID());
	CityBench.obMap.put(observation.toString(), so);
	observation.addProperty(RDF.type, m.createResource(RDFFileManager.ssnPrefix + "Observation"));
	// observation.addProperty(RDF.type,
	// m.createResource(RDFFileManager.saoPrefix + "StreamData"));
	Resource serviceID = m.createResource(ed.getServiceId());
	observation.addProperty(m.createProperty(RDFFileManager.ssnPrefix + "observedBy"), serviceID);
	// Resource property = m.createResource(s.split("\\|")[2]);
	// property.addProperty(RDF.type, m.createResource(s.split("\\|")[0]));
	observation.addProperty(m.createProperty(RDFFileManager.ssnPrefix + "observedProperty"),
			m.createResource(ed.getPayloads().get(0).split("\\|")[2]));
	Property hasValue = m.createProperty(RDFFileManager.saoPrefix + "hasValue");
	// Literal l;
	// System.out.println("Annotating: " + observedProperty.toString());
	// if (observedProperty.contains("AvgSpeed"))
	observation.addLiteral(hasValue, ((AarhusParkingObservation) so).getVacancies());
	// observation.addLiteral(m.createProperty(RDFFileManager.ssnPrefix + "featureOfInterest"),
	// ((AarhusParkingObservation) so).getGarageCode());
	return m.listStatements().toList();
}
 
Example #15
Source File: CQELSAarhusParkingStream.java    From Benchmark with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected List<Statement> getStatements(SensorObservation so) {
	Model m = ModelFactory.createDefaultModel();
	Resource observation = m.createResource(RDFFileManager.defaultPrefix + so.getObId() + UUID.randomUUID());
	CityBench.obMap.put(observation.toString(), so);
	observation.addProperty(RDF.type, m.createResource(RDFFileManager.ssnPrefix + "Observation"));
	// observation.addProperty(RDF.type,
	// m.createResource(RDFFileManager.saoPrefix + "StreamData"));
	Resource serviceID = m.createResource(ed.getServiceId());
	observation.addProperty(m.createProperty(RDFFileManager.ssnPrefix + "observedBy"), serviceID);
	// Resource property = m.createResource(s.split("\\|")[2]);
	// property.addProperty(RDF.type, m.createResource(s.split("\\|")[0]));
	observation.addProperty(m.createProperty(RDFFileManager.ssnPrefix + "observedProperty"),
			m.createResource(ed.getPayloads().get(0).split("\\|")[2]));
	Property hasValue = m.createProperty(RDFFileManager.saoPrefix + "hasValue");
	// Literal l;
	// System.out.println("Annotating: " + observedProperty.toString());
	// if (observedProperty.contains("AvgSpeed"))
	observation.addLiteral(hasValue, ((AarhusParkingObservation) so).getVacancies());
	// observation.addLiteral(m.createProperty(RDFFileManager.ssnPrefix + "featureOfInterest"),
	// ((AarhusParkingObservation) so).getGarageCode());
	return m.listStatements().toList();
}
 
Example #16
Source File: CQELSAarhusPollutionStream.java    From Benchmark with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected List<Statement> getStatements(SensorObservation so) {
	Model m = ModelFactory.createDefaultModel();
	if (ed != null)
		for (String s : ed.getPayloads()) {
			Resource observation = m
					.createResource(RDFFileManager.defaultPrefix + so.getObId() + UUID.randomUUID());
			// so.setObId(RDFFileManager.defaultPrefix + observation.toString());
			CityBench.obMap.put(observation.toString(), so);
			observation.addProperty(RDF.type, m.createResource(RDFFileManager.ssnPrefix + "Observation"));

			Resource serviceID = m.createResource(ed.getServiceId());
			observation.addProperty(m.createProperty(RDFFileManager.ssnPrefix + "observedBy"), serviceID);
			observation.addProperty(m.createProperty(RDFFileManager.ssnPrefix + "observedProperty"),
					m.createResource(s.split("\\|")[2]));
			Property hasValue = m.createProperty(RDFFileManager.saoPrefix + "hasValue");
			observation.addLiteral(hasValue, ((PollutionObservation) so).getApi());
		}
	return m.listStatements().toList();
}
 
Example #17
Source File: CQELSAarhusWeatherStream.java    From Benchmark with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected List<Statement> getStatements(SensorObservation wo) throws NumberFormatException, IOException {
	Model m = ModelFactory.createDefaultModel();
	if (ed != null)
		for (String s : ed.getPayloads()) {
			Resource observation = m
					.createResource(RDFFileManager.defaultPrefix + wo.getObId() + UUID.randomUUID());
			// wo.setObId(observation.toString());
			CityBench.obMap.put(observation.toString(), wo);
			observation.addProperty(RDF.type, m.createResource(RDFFileManager.ssnPrefix + "Observation"));
			Resource serviceID = m.createResource(ed.getServiceId());
			observation.addProperty(m.createProperty(RDFFileManager.ssnPrefix + "observedBy"), serviceID);
			observation.addProperty(m.createProperty(RDFFileManager.ssnPrefix + "observedProperty"),
					m.createResource(s.split("\\|")[2]));
			Property hasValue = m.createProperty(RDFFileManager.saoPrefix + "hasValue");
			if (s.contains("Temperature"))
				observation.addLiteral(hasValue, ((WeatherObservation) wo).getTemperature());
			else if (s.toString().contains("Humidity"))
				observation.addLiteral(hasValue, ((WeatherObservation) wo).getHumidity());
			else if (s.toString().contains("WindSpeed"))
				observation.addLiteral(hasValue, ((WeatherObservation) wo).getWindSpeed());
		}
	return m.listStatements().toList();
}
 
Example #18
Source File: RDFFileManager.java    From Benchmark with GNU General Public License v3.0 6 votes vote down vote up
public static EventPattern extractQueryFromDataset(String serviceRequest) {
	Model queryBase = FileManager.get().loadModel(datasetDirectory + serviceRequest);
	dataset.getDefaultModel().add(ModelFactory.createOntologyModel(ontoSpec, queryBase));

	String describeStr = queryPrefix + " select ?x  where{?x rdf:type ces:EventRequest}";
	// Query query = QueryFactory.create(describeStr);
	// query.setPrefixMapping(pmap);
	QueryExecution qe = QueryExecutionFactory.create(describeStr, dataset);
	ResultSet results = qe.execSelect();
	// ResultSetFormatter.out(System.out, results, query);
	Map<String, EventDeclaration> edMap = new HashMap<String, EventDeclaration>();
	EventPattern ep = new EventPattern();
	ep.setQuery(true);
	while (results.hasNext()) {
		// System.out.println("results!");
		QuerySolution row = results.next();
		RDFNode edID = row.get("x");
		// System.out.println("has id: " + edID.toString());
		ep = extractEDByServiceID(edID, dataset, edMap).getEp();
	}
	return ep;
}
 
Example #19
Source File: RDFFileManager.java    From Benchmark with GNU General Public License v3.0 6 votes vote down vote up
public static EventPattern extractCompositionPlanFromDataset(String serviceRequest) {
	Model queryBase = FileManager.get().loadModel(datasetDirectory + serviceRequest);
	dataset.getDefaultModel().add(ModelFactory.createOntologyModel(ontoSpec, queryBase));

	String describeStr = queryPrefix + " select ?x  where{?x rdf:type ces:CompositionPlan}";
	// Query query = QueryFactory.create(describeStr);
	// query.setPrefixMapping(pmap);
	QueryExecution qe = QueryExecutionFactory.create(describeStr, dataset);
	ResultSet results = qe.execSelect();
	// ResultSetFormatter.out(System.out, results, query);
	Map<String, EventDeclaration> edMap = new HashMap<String, EventDeclaration>();
	EventPattern ep = new EventPattern();
	ep.setQuery(false);
	while (results.hasNext()) {
		// System.out.println("results!");
		QuerySolution row = results.next();
		RDFNode edID = row.get("x");
		// System.out.println("has id: " + edID.toString());
		ep = extractEDByServiceID(edID, dataset, edMap).getEp();
	}
	return ep;
}
 
Example #20
Source File: RDFFileManager.java    From Benchmark with GNU General Public License v3.0 6 votes vote down vote up
public static EventPattern extractQueryFromModel(Model serviceRequest) {
	// Model queryBase = FileManager.get().loadModel(datasetDirectory + serviceRequest);
	dataset.getDefaultModel().add(ModelFactory.createOntologyModel(ontoSpec, serviceRequest));

	String describeStr = queryPrefix + " select ?x  where{?x rdf:type ces:EventRequest}";
	// Query query = QueryFactory.create(describeStr);
	// query.setPrefixMapping(pmap);
	QueryExecution qe = QueryExecutionFactory.create(describeStr, dataset);
	ResultSet results = qe.execSelect();
	// ResultSetFormatter.out(System.out, results, query);
	Map<String, EventDeclaration> edMap = new HashMap<String, EventDeclaration>();
	EventPattern ep = new EventPattern();

	while (results.hasNext()) {
		// System.out.println("results!");
		QuerySolution row = results.next();
		RDFNode edID = row.get("x");
		// System.out.println("has id: " + edID.toString());
		ep = extractEDByServiceID(edID, dataset, edMap).getEp();
	}
	return ep;
}
 
Example #21
Source File: Course_Test.java    From neo4jena with Apache License 2.0 6 votes vote down vote up
public static void getJob(GraphDatabaseService njgraph)
{
	NeoGraph graph = new NeoGraph(njgraph);
	Model njmodel = ModelFactory.createModelForGraph(graph);
	
	ST descJob = TemplateLoader.getQueriesGroup().getInstanceOf("getGraph");
	String queryASString = Constants.QUERY_PREFIX+ descJob.render();
	
	Query query = QueryFactory.create(queryASString, Syntax.syntaxSPARQL_11);
	QueryExecution qexec = QueryExecutionFactory.create(query, njmodel);
	ResultSet res = qexec.execSelect();
	
	int count=0;
       while(res.hasNext()){
       	//System.out.println("in while"+count);
       	QuerySolution sol = res.next();
       	System.out.println(sol.get("?Z"));
       	count++;
       }
      
      //log.info("Record fetched:"+ count);
      System.out.println("Record fetched:"+ count);
}
 
Example #22
Source File: Course_Test.java    From neo4jena with Apache License 2.0 6 votes vote down vote up
public static void insertData(GraphDatabaseService njgraph){
	NeoGraph graph = new NeoGraph(njgraph);
	Model njmodel = ModelFactory.createModelForGraph(graph);
	
	String s2 = "prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n" +
           	"PREFIX uni: <http://seecs.edu.pk/db885#>" +
           	"PREFIX foaf: <http://xmlns.com/foaf/0.1/> " +
           "INSERT DATA "+
           "{ " +
           " <http://seecs.edu.pk/db885#KhalidLatif> rdf:type uni:Professor ."+
           "}"; 
	StopWatch watch = new StopWatch();
	UpdateAction.parseExecute(s2, njmodel);
	System.out.println("Insert query took: " + watch.stop() + " ms");
	log.info("Data inserted");
	System.out.println("Data inserted");
}
 
Example #23
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 #24
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 #25
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 #26
Source File: Validator.java    From aliada-tool with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Validates the collected sample.
 * 
 * @param resource the Job resource representation (i.e. the sample owner).
 * @param exchange the current exchange.
 */
public void validate(final JobResource resource, final Exchange exchange) {
	log.info(MessageCatalog._00055_VALIDATING, resource.getID());

	resource.markAsValidated();

	collectSample(resource.getID(), exchange.getIn().getBody(String.class));
	
	final InfModel infmodel = ModelFactory.createInfModel(reasoner, samples.remove(resource.getID()));
       final ValidityReport validity = infmodel.validate();
       if (!validity.isClean()) {
       	log.info(MessageCatalog._00057_VALIDATION_KO, resource.getID());
       	for (final Iterator<ValidityReport.Report> iterator = validity.getReports(); iterator.hasNext(); ) {
       		final ValidityReport.Report report = iterator.next();
       		validationMessageRepository.save(new ValidationMessage(resource.getID(), report.getType(), report.getDescription()));
        	log.info(MessageCatalog._00058_VALIDATION_MSG, resource.getID(), report.getDescription(), report.getType());
       	}
        resource.setRunning(false);
        exchange.setProperty(Exchange.ROUTE_STOP, Boolean.TRUE); 
       } else {
        log.info(MessageCatalog._00056_VALIDATION_OK, resource.getID());
       }		
}
 
Example #27
Source File: DataWrapper.java    From Benchmark with GNU General Public License v3.0 6 votes vote down vote up
public static List<Statement> getAarhusPollutionStatement(SensorObservation so, EventDeclaration ed) {
	Model m = ModelFactory.createDefaultModel();
	if (ed != null)
		for (String s : ed.getPayloads()) {
			Resource observation = m
					.createResource(RDFFileManager.defaultPrefix + so.getObId() + UUID.randomUUID());
			// so.setObId(RDFFileManager.defaultPrefix + observation.toString());
			CityBench.obMap.put(observation.toString(), so);
			observation.addProperty(RDF.type, m.createResource(RDFFileManager.ssnPrefix + "Observation"));

			Resource serviceID = m.createResource(ed.getServiceId());
			observation.addProperty(m.createProperty(RDFFileManager.ssnPrefix + "observedBy"), serviceID);
			observation.addProperty(m.createProperty(RDFFileManager.ssnPrefix + "observedProperty"),
					m.createResource(s.split("\\|")[2]));
			Property hasValue = m.createProperty(RDFFileManager.saoPrefix + "hasValue");
			observation.addLiteral(hasValue, ((PollutionObservation) so).getApi());
		}
	return m.listStatements().toList();
}
 
Example #28
Source File: DecompositionRDFWriter.java    From TableDisentangler with GNU General Public License v3.0 5 votes vote down vote up
public DecompositionRDFWriter(String url)
{
	ArticleDefault = url;
	model = ModelFactory.createDefaultModel();
	ArticleName = model.createProperty( ArticleDefault + "ArticleName" );
	ArticleID = model.createProperty( ArticleDefault + "ArticleID" );
	hasAuthor = model.createProperty( ArticleDefault + "hasAuthor" );
	Publisher =  model.createProperty( ArticleDefault + "Publisher" );
	Abstract = model.createProperty( ArticleDefault + "Abstract" );
	Venue = model.createProperty( ArticleDefault + "Venue" );
	ShortAbstract = model.createProperty( ArticleDefault + "ShortAbstract" );
	hasAffiliation = model.createProperty( ArticleDefault + "hasAffiliation" );
	Keywords = model.createProperty( ArticleDefault + "KeyWord" );
	TableOrder = model.createProperty( ArticleDefault + "TableOrder" );
	TableCaption = model.createProperty( ArticleDefault + "TableCaption" );
	TableFooter = model.createProperty( ArticleDefault + "TableFooter" );
	Table = model.createProperty( ArticleDefault + "HasTable" );
	TableType = model.createProperty( ArticleDefault + "TableType" );
	TablePragmaticType = model.createProperty( ArticleDefault + "TablePragmaticType" );
	TableXML= model.createProperty( ArticleDefault + "TableXML" );
	Cell = model.createProperty( ArticleDefault + "HasCell" );
	CellStub = model.createProperty( ArticleDefault + "CellStub" );
	CellStubValue = model.createProperty( ArticleDefault + "CellStubValue" );
	CellSubheadeing = model.createProperty( ArticleDefault + "CellSubheadeing" );
	CellHeader = model.createProperty( ArticleDefault + "CellHeader" );
	CellValue = model.createProperty( ArticleDefault + "CellValue" );
	CellType = model.createProperty( ArticleDefault + "CellType" );
	CellRow = model.createProperty( ArticleDefault + "CellRow" );
	HasNavigationalPath = model.createProperty( ArticleDefault + "HasNavigationalPath" );
	CellColumn = model.createProperty( ArticleDefault + "CellColumn" );
	Head00 = model.createProperty( ArticleDefault + "Head00" );
	NavigationalPath = model.createProperty( ArticleDefault + "NavigationalPath" );
	Root = model.createResource(ArticleDefault+"Root");
	HasArticle = model.createProperty( ArticleDefault + "HasArticle" );
}
 
Example #29
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 #30
Source File: Course_Test.java    From neo4jena with Apache License 2.0 5 votes vote down vote up
public static void search(GraphDatabaseService njgraph) {
	NeoGraph graph = new NeoGraph(njgraph);
	Model njmodel = ModelFactory.createModelForGraph(graph);
	
	String s2 = "prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n" +
               	"PREFIX uni: <http://seecs.edu.pk/db885#>" +
               	"PREFIX foaf: <http://xmlns.com/foaf/0.1/> " +
               "SELECT ?X ?Z ?Y "+
               "WHERE" +
               "{ ?X ?Z ?Y ." +
               "}"; 
      	          
       Query query = QueryFactory.create(s2); 
       QueryExecution qExe = QueryExecutionFactory.create(query, njmodel);
       StopWatch watch = new StopWatch();
       ResultSet results = qExe.execSelect();
       long endTime = watch.stop();
       log.info("Query took (ms): "+endTime);
       System.out.println("Query took (ms): "+ endTime);
      // ResultSetFormatter.out(System.out, results);
       
       int count=0;
       while(results.hasNext()){
       	//System.out.println("in while"+count);
       	QuerySolution sol = results.next();
       	System.out.println(sol.get("?Z"));
       	count++;
       }
      
      log.info("Record fetched:"+ count);
      System.out.println("Record fetched:"+ count);
}