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

The following examples show how to use com.hp.hpl.jena.rdf.model.Model#add() . 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: 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 2
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 3
Source File: Mapping.java    From xcurator with Apache License 2.0 6 votes vote down vote up
public static Set<String> getAllTypes(Model model, String typePrefix) {
    Resource rootResource = model.createResource(typePrefix);

    com.hp.hpl.jena.rdf.model.Property classProperty = model.createProperty("http://dblab.cs.toronto.edu/project/xcurator/0.1#classes");
    Bag classBag = model.createBag("http://dblab.cs.toronto.edu/project/xcurator/0.1#classBag");
    model.add(rootResource, classProperty, classBag);

    Set<String> ret = new HashSet<String>();

    NodeIterator iterator = classBag.iterator();
    while (iterator.hasNext()) {
        Resource resource = (Resource) iterator.next();
        ret.add(resource.getURI());
    }

    return ret;
}
 
Example 4
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 5
Source File: SPARQLEndPoint.java    From LodView with MIT License 6 votes vote down vote up
public Model extractLocalData(Model result, String IRI, Model m, List<String> queries) throws Exception {

		// System.out.println("executing query on IRI");
		Resource subject = result.createResource(IRI);
		for (String query : queries) {
			QueryExecution qe = QueryExecutionFactory.create(parseQuery(query, IRI, null, -1, null), m);
			try {
				ResultSet rs = qe.execSelect();
				List<Statement> sl = new ArrayList<Statement>();
				while (rs.hasNext()) {
					QuerySolution qs = rs.next();
					RDFNode subject2 = qs.get("s");
					RDFNode property = qs.get("p");
					RDFNode object = qs.get("o");
					result.add(result.createStatement(subject2 != null ? subject2.asResource() : subject, property.as(Property.class), object));
				}
				result.add(sl);
			} catch (Exception e) {
				e.printStackTrace();
				throw new Exception("error in query execution: " + e.getMessage());
			} finally {
				qe.close();
			}
		}
		return result;
	}
 
Example 6
Source File: JenaSesameUtils.java    From anno4j with Apache License 2.0 5 votes vote down vote up
/**
 * Convert the Sesame Graph to a Jena Model
 * @param theGraph the Graph to convert
 * @return the set of statements in the Sesame Graph converted and saved in a Jena Model
 */
public static Model asJenaModel(Graph theGraph) {
    Model aModel = ModelFactory.createDefaultModel();

    for (final org.openrdf.model.Statement aStmt : theGraph) {
        aModel.add(asJenaStatement(aStmt));
    }

    return aModel;
}
 
Example 7
Source File: VocabularySummarizer.java    From GeoTriples with Apache License 2.0 5 votes vote down vote up
public Model triplesInvolvingVocabulary(Model model) {
	Model result = ModelFactory.createDefaultModel();
	result.getNsPrefixMap().putAll(model.getNsPrefixMap());
	StmtIterator it = model.listStatements();
	while (it.hasNext()) {
		Statement stmt = it.next();
		if (properties.contains(stmt.getPredicate())
				|| (stmt.getPredicate().equals(RDF.type) && classes.contains(stmt.getObject()))) {
			result.add(stmt);
		}
	}
	return result;
}
 
Example 8
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 9
Source File: SPARQLEndPoint.java    From LodView with MIT License 5 votes vote down vote up
public Model extractData(Model result, String IRI, String sparql, List<String> queries) throws Exception {

		// System.out.println("executing query on " + sparql);
		Resource subject = result.createResource(IRI);
		for (String query : queries) {
			QueryExecution qe = QueryExecutionFactory.sparqlService(sparql, parseQuery(query, IRI, null, -1, null));
			try {
				ResultSet rs = qe.execSelect();

				List<Statement> sl = new ArrayList<Statement>();
				while (rs.hasNext()) {
					QuerySolution qs = rs.next();
					RDFNode subject2 = qs.get("s");
					RDFNode property = qs.get("p");
					RDFNode object = qs.get("o");
					result.add(result.createStatement(subject2 != null ? subject2.asResource() : subject, property.as(Property.class), object));
				}
				result.add(sl);
			} catch (Exception e) {
				e.printStackTrace();
				throw new Exception("error in query execution: " + e.getMessage());
			} finally {
				qe.close();
			}
		}
		return result;
	}
 
Example 10
Source File: ResourceDescriptionServlet.java    From GeoTriples with Apache License 2.0 4 votes vote down vote up
protected void doGet(HttpServletRequest request,
		HttpServletResponse response) throws IOException, ServletException {
	D2RServer server = D2RServer.fromServletContext(getServletContext());
	server.checkMappingFileChanged();
	String relativeResourceURI = request.getRequestURI().substring(
			request.getContextPath().length()
					+ request.getServletPath().length());
	// Some servlet containers keep the leading slash, some don't
	if (!"".equals(relativeResourceURI)
			&& "/".equals(relativeResourceURI.substring(0, 1))) {
		relativeResourceURI = relativeResourceURI.substring(1);
	}
	if (request.getQueryString() != null) {
		relativeResourceURI = relativeResourceURI + "?"
				+ request.getQueryString();
	}

	/* Determine service stem, i.e. vocab/ in /[vocab/]data */
	int servicePos;
	if (-1 == (servicePos = request.getServletPath().indexOf(
			"/" + D2RServer.getDataServiceName())))
		throw new ServletException("Expected to find service path /"
				+ D2RServer.getDataServiceName());
	String serviceStem = request.getServletPath().substring(1,
			servicePos + 1);

	String resourceURI = RequestParamHandler
			.removeOutputRequestParam(server.resourceBaseURI(serviceStem)
					+ relativeResourceURI);
	String documentURL = server.dataURL(serviceStem, relativeResourceURI);

	String pageURL = server.pageURL(serviceStem, relativeResourceURI);

	String sparqlQuery = "DESCRIBE <" + resourceURI + ">";
	QueryExecution qe = QueryExecutionFactory.create(sparqlQuery,
			server.dataset());
	if (server.getConfig().getPageTimeout() > 0) {
		qe.setTimeout(Math.round(server.getConfig().getPageTimeout() * 1000));
	}
	Model description = qe.execDescribe();
	qe.close();
	
	if (description.size() == 0) {
		response.sendError(404);
	}
	if (description.qnameFor(FOAF.primaryTopic.getURI()) == null
			&& description.getNsPrefixURI("foaf") == null) {
		description.setNsPrefix("foaf", FOAF.NS);
	}
	Resource resource = description.getResource(resourceURI);

	Resource document = description.getResource(documentURL);
	document.addProperty(FOAF.primaryTopic, resource);

	Statement label = resource.getProperty(RDFS.label);
	if (label != null) {
		document.addProperty(RDFS.label,
				"RDF Description of " + label.getString());
	}
	server.addDocumentMetadata(description, document);
	if (server.getConfig().serveMetadata()) {
		// add document metadata from template
		Model resourceMetadataTemplate = server.getConfig().getResourceMetadataTemplate(
				server, getServletContext());
		MetadataCreator resourceMetadataCreator = new MetadataCreator(
				server, resourceMetadataTemplate);
		description.add(resourceMetadataCreator.addMetadataFromTemplate(
				resourceURI, documentURL, pageURL));
		
		Map<String, String> descPrefixes = description.getNsPrefixMap();
		descPrefixes.putAll(resourceMetadataTemplate.getNsPrefixMap());
		description.setNsPrefixes(descPrefixes);
	}
	// TODO: Add a Content-Location header
	new ModelResponse(description, request, response).serve();
}