Java Code Examples for com.hp.hpl.jena.rdf.model.Model

The following examples show how to use com.hp.hpl.jena.rdf.model.Model. These examples are extracted from open source projects. 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 Project: GeoTriples   Source File: WP2RDFXMLWriter.java    License: Apache License 2.0 9 votes vote down vote up
private void writeRDFHeader(Model model, PrintWriter writer) {
	String xmlns = xmlnsDecl();
	writer.print("<" + rdfEl("RDF") + xmlns);
	if (null != xmlBase && xmlBase.length() > 0)
		writer.print("\n  xml:base=" + substitutedAttribute(xmlBase));
	writer.println(" > ");
}
 
Example 2
@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 3
Source Project: micro-integrator   Source File: SPARQLQuery.java    License: Apache License 2.0 6 votes vote down vote up
private Object processPreQuery(InternalParamCollection params, int queryLevel) throws DataServiceFault {
	try {
	    ResultSet results;
           QuerySolutionMap queryMap = new QuerySolutionMap();
           Model model = this.getConfig().createRDFModel();
           /* process the query params */
           for (InternalParam param : params.getParams()) {
               /* set parameters to the querry map */
               queryMap.add(param.getName(), convertTypeLiteral(model, param));
           }
           QueryExecution qe = QueryExecutionFactory.create(this.getQuery(), model);
           qe.setInitialBinding(queryMap) ;
           /* execute querry as a select querry */
           results = qe.execSelect();
           return results;
	} catch (Exception e) {
		throw new DataServiceFault(e, "Error in 'SPARQLQuery.processQuery'");
	}
}
 
Example 4
Source Project: xcurator   Source File: Property.java    License: Apache License 2.0 6 votes vote down vote up
public Resource createRDFProperty(
        Model model, Resource parentResource, Element item, Document dataDoc) throws XPathExpressionException {

    com.hp.hpl.jena.rdf.model.Property jenaProperty = getJenaProperty(model);
    Resource res = null;
    NodeList nodeList = XMLUtils.getNodesByPath(path, item, dataDoc);
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        String value = node.getTextContent();
        res = parentResource.addProperty(jenaProperty, value);
    }

    for (String uri : ontologyTypes) {
        jenaProperty.addProperty(OWL.equivalentProperty, model.createResource(uri));
    }

    return res;
}
 
Example 5
Source Project: Benchmark   Source File: DataWrapper.java    License: 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 6
Source Project: neo4jena   Source File: Course_Test.java    License: 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 7
@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 8
Source Project: EventCoreference   Source File: GetPerspectiveRelations.java    License: Apache License 2.0 6 votes vote down vote up
public static void perspectiveRelationsToTrig (String pathToTrigFile, ArrayList<PerspectiveObject> perspectiveObjects) {
    try {
        OutputStream fos = new FileOutputStream(pathToTrigFile);
        Dataset ds = TDBFactory.createDataset();
        Model defaultModel = ds.getDefaultModel();
        //ResourcesUri.prefixModel(defaultModel);
      //  Model provenanceModel = ds.getNamedModel("http://www.newsreader-project.eu/perspective");
        ResourcesUri.prefixModelGaf(defaultModel);
        String attrBase = pathToTrigFile+"_";
        JenaSerialization.addJenaPerspectiveObjects(attrBase, ResourcesUri.grasp, "wasAttributedTo", perspectiveObjects, 1);
        RDFDataMgr.write(fos, ds, RDFFormat.TRIG_PRETTY);
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }
}
 
Example 9
Source Project: LodView   Source File: ResourceBuilder.java    License: 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 10
Source Project: xcurator   Source File: Mapping.java    License: 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 11
Source Project: Benchmark   Source File: RDFFileManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static Resource createTrafficLocation(Model m, EventDeclaration ed) {
	Resource foi = m.createResource(defaultPrefix + "FoI-" + UUID.randomUUID());
	foi.addProperty(RDF.type, m.createResource(ssnPrefix + "FeatureOfInterest"));
	Resource firstNode = m.createResource();
	firstNode.addProperty(RDF.type, m.createResource(ctPrefix + "Node"));
	foi.addProperty(m.createProperty(ctPrefix + "hasFirstNode"), firstNode);
	firstNode.addLiteral(m.createProperty(ctPrefix + "hasStreetNumber"),
			((TrafficReportService) ed).getNode1StreetNo());
	firstNode.addLiteral(m.createProperty(ctPrefix + "hasStreet"), ((TrafficReportService) ed).getNode1Street());
	firstNode.addLiteral(m.createProperty(ctPrefix + "hasCity"), ((TrafficReportService) ed).getNode1City());
	firstNode.addLiteral(m.createProperty(ctPrefix + "hasLatitude"), ((TrafficReportService) ed).getNode1Lat());
	firstNode.addLiteral(m.createProperty(ctPrefix + "hasLongtitude"), ((TrafficReportService) ed).getNode1Lon());
	firstNode.addLiteral(m.createProperty(ctPrefix + "hasNodeName"), ((TrafficReportService) ed).getNode1Name());

	Resource secNode = m.createResource();
	secNode.addProperty(RDF.type, ctPrefix + "Node");
	foi.addProperty(m.createProperty(ctPrefix + "hasSecondNode"), secNode);
	secNode.addLiteral(m.createProperty(ctPrefix + "hasStreetNumber"),
			((TrafficReportService) ed).getNode2StreetNo());
	secNode.addLiteral(m.createProperty(ctPrefix + "hasStreet"), ((TrafficReportService) ed).getNode2Street());
	secNode.addLiteral(m.createProperty(ctPrefix + "hasCity"), ((TrafficReportService) ed).getNode2City());
	secNode.addLiteral(m.createProperty(ctPrefix + "hasLatitude"), ((TrafficReportService) ed).getNode2Lat());
	secNode.addLiteral(m.createProperty(ctPrefix + "hasLongtitude"), ((TrafficReportService) ed).getNode2Lon());
	secNode.addLiteral(m.createProperty(ctPrefix + "hasNodeName"), ((TrafficReportService) ed).getNode2Name());
	return foi;
}
 
Example 12
Source Project: Benchmark   Source File: RDFFileManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static void createSelections(Resource patternNode, Model m, EventPattern ep) {
	Property hasSelection = m.createProperty(cesPrefix + "hasSelection");
	Property hasNodeId = m.createProperty(cesPrefix + "hasNodeId");
	Property hasSelectedProperty = m.createProperty(cesPrefix + "selectedProperty");
	// System.out.p rintln("Creating selections:------------");
	for (Selection sel : ep.getSelections()) {
		// System.out.println("SEL: " + sel.toString());
		Resource pName = m.createResource(sel.getPropertyName());
		String nodeId = sel.getProvidedBy();
		// Resource pType = m.createResource(sel.getPropertyType());
		// EventDeclaration ed;
		// if (ep.isQuery() && sel.getOriginalED() != null)
		// ed = sel.getOriginalED();
		// Resource foi = m.createResource(sel.getFoi());
		patternNode.addProperty(
				hasSelection,
				m.createResource().addProperty(RDF.type, m.createResource(cesPrefix + "Selection"))
						.addProperty(hasNodeId, m.createLiteral(nodeId)).addProperty(hasSelectedProperty, pName));
		// if (ep.isQuery()) {// add property type and foi for query
		// pName.addProperty(RDF.type, pType).addProperty(m.createProperty(ssnPrefix + "isPropertyOf"), foi);
		// }
	}
}
 
Example 13
@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 14
Source Project: SolRDF   Source File: IntegrationTestSupertypeLayer.java    License: Apache License 2.0 6 votes vote down vote up
protected void assertIsomorphic(final Model memoryModel, final Model solrdfModel, final String uri) {
	try {
		assertTrue(solrdfModel.isIsomorphicWith(memoryModel));
	} catch (Throwable exception) {
		final StringWriter memoryModelWriter = new StringWriter();
		final StringWriter remoteModelWriter = new StringWriter();
		RDFDataMgr.write(memoryModelWriter, memoryModel, RDFFormat.NTRIPLES) ;
		RDFDataMgr.write(remoteModelWriter, solrdfModel, RDFFormat.NQUADS) ;

		final String name = uri != null ? uri : " (DEFAULT) ";
		log.debug("**** MEMORY MODEL " + name + " ****");
		log.debug(memoryModelWriter.toString());
		log.debug("");
		log.debug("**** REMOTE MODEL " + name + " ****");
		log.debug(remoteModelWriter.toString());
		log.debug("*********************************");
		throw exception;
	}
}
 
Example 15
Source Project: GeoTriples   Source File: VocabularySummarizer.java    License: Apache License 2.0 6 votes vote down vote up
public Collection<Resource> getUndefinedResources(Model model) {
	Set<Resource> result = new HashSet<Resource>();
	StmtIterator it = model.listStatements();
	while (it.hasNext()) {
		Statement stmt = it.nextStatement();
		if (stmt.getSubject().isURIResource()
				&& stmt.getSubject().getURI().startsWith(namespace)
				&& !resources.contains(stmt.getSubject())) {
			result.add(stmt.getSubject());
		}
		if (stmt.getPredicate().equals(RDF.type)) continue;
		if (stmt.getObject().isURIResource()
				&& stmt.getResource().getURI().startsWith(namespace)
				&& !resources.contains(stmt.getResource())) {
			result.add(stmt.getResource());
		}
	}
	return result;
}
 
Example 16
Source Project: GeoTriples   Source File: VocabularySummarizer.java    License: Apache License 2.0 6 votes vote down vote up
public void assertNoUndefinedTerms(Model model, 
		int undefinedPropertyErrorCode, int undefinedClassErrorCode) {
	Collection<Property> unknownProperties = getUndefinedProperties(model);
	if (!unknownProperties.isEmpty()) {
		throw new D2RQException(
				"Unknown property " + PrettyPrinter.toString(
						unknownProperties.iterator().next()) + ", maybe a typo?",
				undefinedPropertyErrorCode);
	}
	Collection<Resource> unknownClasses = getUndefinedClasses(model);
	if (!unknownClasses.isEmpty()) {
		throw new D2RQException(
				"Unknown class " + PrettyPrinter.toString(
						unknownClasses.iterator().next()) + ", maybe a typo?",
				undefinedClassErrorCode);
	}
}
 
Example 17
Source Project: xcurator   Source File: Entity.java    License: Apache License 2.0 6 votes vote down vote up
private Object getSameResource(Model model, String typePrefix,
        Element item, Document dataDoc) throws XPathExpressionException {
    QueryExecution qExec = null;
    try {
        String query = getEqualsQuery(model, typePrefix, item, dataDoc);
        LogUtils.debug(this.getClass(), query);
        qExec = QueryExecutionFactory.create(query, model);
        ResultSet rs = qExec.execSelect();
        while (rs.hasNext()) {
            QuerySolution solution = rs.next();
            return solution.get("?x0");
        }
    } catch (Exception e) {
        if (debug) {
            e.printStackTrace();
        }
    } finally {
        if (qExec != null) {
            qExec.close();
        }
    }
    return null;
}
 
Example 18
@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 19
Source Project: Benchmark   Source File: RDFFileManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static void createQoSModel(Resource profile, Model m, EventDeclaration ed) {
	if (ed.getInternalFrequency() != null) {
		createQosParam(profile, "Frequency", ed.getInternalFrequency(), m);
	}
	if (ed.getInternalQos() != null) {
		QosVector qos = ed.getInternalQos();
		Double a = qos.getAccuracy();
		Double r = qos.getReliability();
		int l = qos.getLatency();
		int p = qos.getPrice();
		int s = qos.getSecurity();
		createQosParam(profile, "Accuracy", a, m);
		createQosParam(profile, "Reliability", r, m);
		createQosParam(profile, "Latency", l, m);
		createQosParam(profile, "Price", p, m);
		createQosParam(profile, "Security", s, m);
	}

}
 
Example 20
Source Project: EventCoreference   Source File: RdfReader.java    License: 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 21
Source Project: Benchmark   Source File: RDFFileManager.java    License: 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 22
Source Project: SolRDF   Source File: FromAndFromNamedClauses_ITCase.java    License: 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 23
Source Project: GeoTriples   Source File: ClassMapServlet.java    License: Apache License 2.0 6 votes vote down vote up
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	D2RServer server = D2RServer.fromServletContext(getServletContext());
	server.checkMappingFileChanged();
	if (request.getPathInfo() == null) {
		new ModelResponse(classMapListModel(), request, response).serve();
		return;
	}
	String classMapName = request.getPathInfo().substring(1);
	Model resourceList = server.getMapping().getResourceCollection(classMapName).getInventoryModel();
	if (resourceList == null) {
		response.sendError(404, "Sorry, class map '" + classMapName + "' not found.");
		return;
	}
   	Resource classMap = resourceList.getResource(server.baseURI() + "all/" + classMapName);
   	Resource directory = resourceList.createResource(server.baseURI() + "all");
   	classMap.addProperty(RDFS.seeAlso, directory);
   	classMap.addProperty(RDFS.label, "List of all instances: " + classMapName);
   	directory.addProperty(RDFS.label, "D2R Server contents");
   	server.addDocumentMetadata(resourceList, classMap);
	new ModelResponse(resourceList, request, response).serve();
}
 
Example 24
Source Project: ldp4j   Source File: TestingUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static Model asModel(String data, URL base, String path) {
	String language="TURTLE";
	return
		ModelFactory.
			createDefaultModel().
				read(
					new StringReader(data),
					resolve(base,path),
					language);
}
 
Example 25
Source Project: micro-integrator   Source File: RDFConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean isActive() {
	try {
		Model model = this. createRDFModel();
		return model != null;
	} catch (Exception e) {
		log.error("Error in checking RDF config availability", e);
		return false;
	}
}
 
Example 26
Source Project: anno4j   Source File: JenaSesameUtils.java    License: 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 27
Source Project: EventCoreference   Source File: SemTime.java    License: Apache License 2.0 5 votes vote down vote up
public void addToJenaModelTimeInterval(Model model) {
    this.getOwlTime().addToJenaModelOwlTimeInstant(model);

    Resource resource = model.createResource(this.getURI());
    for (int i = 0; i < this.getPhraseCounts().size(); i++) {
        PhraseCount phraseCount = this.getPhraseCounts().get(i);
        if (!phraseCount.getPhrase().isEmpty()) {
            resource.addProperty(RDFS.label, model.createLiteral(phraseCount.getPhrase()));
        }
    }

    resource.addProperty(RDF.type, Sem.Time);

    Resource interval = model.createResource(ResourcesUri.owltime + "Interval");
    resource.addProperty(RDF.type, interval);

    Resource value = model.createResource(this.getOwlTime().getDateStringURI());
    Property property = model.createProperty(ResourcesUri.owltime + "inDateTime");
    resource.addProperty(property, value);

    for (int i = 0; i < this.getNafMentions().size(); i++) {
        NafMention nafMention = this.getNafMentions().get(i);
        Property gaf = model.createProperty(ResourcesUri.gaf + "denotedBy");
        Resource targetResource = model.createResource(nafMention.toString());
        resource.addProperty(gaf, targetResource);

    }

}
 
Example 28
Source Project: EventCoreference   Source File: SemTime.java    License: Apache License 2.0 5 votes vote down vote up
public void addToJenaModelTimeInstant(Model model, OwlTime owlTime) {
    this.getOwlTime().addToJenaModelOwlTimeInstant(model);

    Resource resource = model.createResource(this.getURI());
    for (int i = 0; i < this.getPhraseCounts().size(); i++) {
        PhraseCount phraseCount = this.getPhraseCounts().get(i);
        if (!phraseCount.getPhrase().isEmpty()) {
            resource.addProperty(RDFS.label, model.createLiteral(phraseCount.getPhrase()));
        }
    }

    resource.addProperty(RDF.type, Sem.Time);

    Resource aResource = model.createResource(ResourcesUri.owltime + "Instant");
    resource.addProperty(RDF.type, aResource);

    Resource value = model.createResource(owlTime.getDateStringURI());
    Property property = model.createProperty(ResourcesUri.owltime + "inDateTime");
    resource.addProperty(property, value);

    for (int i = 0; i < this.getNafMentions().size(); i++) {
        NafMention nafMention = this.getNafMentions().get(i);
        Property gaf = model.createProperty(ResourcesUri.gaf + "denotedBy");
        Resource targetResource = model.createResource(nafMention.toString());
        resource.addProperty(gaf, targetResource);
    }
}
 
Example 29
Source Project: xcurator   Source File: RdfGeneratorTest2.java    License: Apache License 2.0 5 votes vote down vote up
@Test
    // Run test_discoverMapping_fb_XBRL to generate the mapping file before running
    // this test.
    public void test_generateRdfs_fb_XBRL() throws SAXException, IOException, ParserConfigurationException {
        // Setup deserializer
        mappingDeserialization = new XmlBasedMappingDeserialization(
                new FileInputStream("output/fb-20121231-mapping.xml"), parser);

        Document dataDocument = parser.parse(RdfGeneratorTest2.class.getResourceAsStream(
                "/secxbrls/data/fb-20121231.xml"), -1);
        rdfGenerator = new RdfGenerator(new DataDocument(dataDocument), new XmlBasedMapping());

        // Add steps
        rdfGenerator.addStep(mappingDeserialization);
        rdfGenerator.addStep(rdfGeneration);

        // Generate
        rdfGenerator.generateRdfs();

        // Verify
        Model model = TDBFactory.createModel(testTdbDir);
        Assert.assertFalse("No RDF was generated. TDB directory: " + testTdbDir, model.isEmpty());

        Resource r = model.getResource("http://example.org/resource/class/unitNumerator");
        // Failing, investigate
        Assert.assertTrue(r.hasProperty(model.getProperty("http://example.org/resource/property/measure")));

//    ResIterator iter = model.listResourcesWithProperty(RDF.type);
//    while (iter.hasNext()) {
//      Resource resource = iter.nextResource();
//      System.out.println(resource.getLocalName());
//      StmtIterator iterStm = resource.listProperties();
//      while (iterStm.hasNext()) {
//        System.out.println(iterStm.nextStatement().toString());
//      }
//    }
    }
 
Example 30
Source Project: xcurator   Source File: RdfGeneratorTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Run the RDF generator pipeline for clinical trial data Before running
 * this, run the Mapping Discovery Test first to generate the mapping file
 * for clinical trials.
 *
 * @throws SAXException
 * @throws IOException
 * @throws ParserConfigurationException
 */
@Test
public void test_generateRdfs_clinical_trials() throws SAXException, IOException, ParserConfigurationException {
    // Setup deserializer
    mappingDeserialization = new XmlBasedMappingDeserialization(
            new FileInputStream("output/clinicaltrials-mapping.xml"), parser);

    Document dataDocument = parser.parse(RdfGeneratorTest.class.getResourceAsStream(
            "/clinicaltrials/data/content.xml"), 10);
    rdfGenerator = new RdfGenerator(new DataDocument(dataDocument), new XmlBasedMapping());

    // Add steps
    rdfGenerator.addStep(mappingDeserialization);
    rdfGenerator.addStep(rdfGeneration);

    // Generate
    rdfGenerator.generateRdfs();

    // Verify
    Model model = TDBFactory.createModel(testTdbDir);
    Assert.assertFalse("No RDF was generated. TDB directory: " + testTdbDir, model.isEmpty());

    ResIterator iter = model.listResourcesWithProperty(RDF.type);
    while (iter.hasNext()) {
        Resource resource = iter.nextResource();
        System.out.println(resource.getLocalName());
        StmtIterator iterStm = resource.listProperties();
        while (iterStm.hasNext()) {
            System.out.println(iterStm.nextStatement().toString());
        }
    }
}