Can someone give me a working example (in Java code) of how to create a RDFS related statement like the following using Jena?
<rdf:Property rdf:about="http://www.help.me/confused/PropertyName">
<rdfs:domain rdf:resource="http://www.help.me/confused/ClassName"/>
<rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/>
</rdf:Property>
I created a RDF/XML schema by hand, and it validates right but somehow the entities won't work together in SPARQL (even with inference engine on). So, I decided to create the whole thing from start using the Jena API to ensure that it's correct.
I've changed the namespace a bit, just so that this code ends up pointing back to this post, but at any rate, I get this output:
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#">
<rdf:Property rdf:about="http://stackoverflow.com/q/20194409/1281433/PropertyName">
<rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/>
<rdfs:domain rdf:resource="http://stackoverflow.com/q/20194409/1281433/ClassName"/>
</rdf:Property>
</rdf:RDF>
from this code:
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.vocabulary.RDFS;
public class JenaPropertyExample {
public static void main(String[] args) {
final String NS = "http://stackoverflow.com/q/20194409/1281433/";
final Model model = ModelFactory.createDefaultModel();
final Property p = model.createResource( NS+"PropertyName", RDF.Property ).as( Property.class );
p.addProperty( RDFS.domain, model.createResource( NS+"ClassName" ));
p.addProperty( RDFS.range, RDFS.Literal );
model.write( System.out, "RDF/XML-ABBREV" );
}
}
In general, just because the output is legal RDF doesn't mean that you're using the properties and classes in the way that's expected. Jena's plain Model interface can't help you too much with that, since you could still use the properties incorrectly, but at least, if you're using Jena's predefined vocabulary classes, you'll get the IRIs right. If you can use an OntModel, you can get a slightly nicer layer of abstraction, though. E.g., the following method produces the same RDF/XML output, but lets you use methods like createOntProperty and get the p rdf:type rdf:Property triple for free, and methods like addRange and addDomain:
public static void main2( String[] args ) {
final String NS = "http://stackoverflow.com/q/20194409/1281433/";
final OntModel model = ModelFactory.createOntologyModel( OntModelSpec.RDFS_MEM );
OntProperty p = model.createOntProperty( NS+"PropertyName" );
p.addDomain( model.getOntClass( NS+"ClassName" ));
p.addRange( RDFS.Literal );
model.write( System.out, "RDF/XML-ABBREV" );
}
Related
I am attempting to port some Java code utilizing Xerces v3.2.2 that loads a schema file, retrieves the XSModel* and parses it into some custom data structures.
JAVA
import org.apache.xerces.XSLoader;
import org.apache.xerces.XSModel;
XSImplementation xsLoader = null;
XSLoader xsLoader = null;
XSModel xsModel = null;
xsImpl = (XSImplmentation) domRegistry.getDOMImplementation("XS-Loader");
xsLoader = xsImpl.createXSLoader(null);
xsModel = xsLoader.loadURI("path-to-schema.xsd");
myDataStruct = new MyDataStruct(xsModel);
I have been unable to find anything in Xerces-c documentation that would yield similar results. As far as I can tell, I can access the XSModel* from the xercesc::GrammarResolver* through the xercesc::AbstractDOMParser but this would require me to derive from the parser as it is a protected function.
CPP
#include <xercesc/parsers/XercesDOMParser.hpp>
using namespace xercesc;
class MyDOMParser : public XercesDOMParser
{
public:
using AbstractDOMParser::getGrammarResolver;
};
int main()
{
XMLPlatformUtils::Initialize();
MyDOMParser parser;
parser.loadGrammar("path-to-schema.xsd", Grammar::GrammarType::SchemaGrammarType);
auto resolver = parser.getGrammarResolver();
auto xsModel = resolver->getXSModel();
MyDataStruct myDataStruct{xsModel};
return 0;
}
Is this the route I must go? Will this even work? Are there examples out in the wild that show a better way of doing this?
The above solution I attempted for CPP does appear to achieve what I'm trying to accomplish. By deriving from XercesDOMParser I am able to access the GrammarResolver and therefore the XSModel. The model seems to contain the data my data structure requires for parsing.
I've been reading the H2O documentation for a while, and I haven't found a clear example of how to load model trained and saved using the Python API. I was following the next example.
import h2o
from h2o.estimators.naive_bayes import H2ONaiveBayesEstimator
model = H2ONaiveBayesEstimator()
h2o_df = h2o.import_file("http://s3.amazonaws.com/h2o-public-test-data/smalldata/airlines/allyears2k_headers.zip")
model.train(y = "IsDepDelayed", x = ["Year", "Origin"],
training_frame = h2o_df,
family = "binomial",
lambda_search = True,
max_active_predictors = 10)
h2o.save_model(model, path=models)
But if you check the official documentation it states that you have to download the model as a POJO from the flow UI. Is it the only way? or, may I achieve the same result via python? Just for information, I show the doc's example below. I need some guidance.
import java.io.*;
import hex.genmodel.easy.RowData;
import hex.genmodel.easy.EasyPredictModelWrapper;
import hex.genmodel.easy.prediction.*;
public class main {
private static String modelClassName = "gbm_pojo_test";
public static void main(String[] args) throws Exception {
hex.genmodel.GenModel rawModel;
rawModel = (hex.genmodel.GenModel) Class.forName(modelClassName).newInstance();
EasyPredictModelWrapper model = new EasyPredictModelWrapper(rawModel);
//
// By default, unknown categorical levels throw PredictUnknownCategoricalLevelException.
// Optionally configure the wrapper to treat unknown categorical levels as N/A instead:
//
// EasyPredictModelWrapper model = new EasyPredictModelWrapper(
// new EasyPredictModelWrapper.Config()
// .setModel(rawModel)
// .setConvertUnknownCategoricalLevelsToNa(true));
RowData row = new RowData();
row.put("Year", "1987");
row.put("Month", "10");
row.put("DayofMonth", "14");
row.put("DayOfWeek", "3");
row.put("CRSDepTime", "730");
row.put("UniqueCarrier", "PS");
row.put("Origin", "SAN");
row.put("Dest", "SFO");
BinomialModelPrediction p = model.predictBinomial(row);
System.out.println("Label (aka prediction) is flight departure delayed: " + p.label);
System.out.print("Class probabilities: ");
for (int i = 0; i < p.classProbabilities.length; i++) {
if (i > 0) {
System.out.print(",");
}
System.out.print(p.classProbabilities[i]);
}
System.out.println("");
}
}
h2o.save_model will save the binary model to the provided file system, however, looking at the Java application above it seems you want to use model into a Java based scoring application.
Because of that you should be using h2o.download_pojo API to save the model to local file system along with genmodel jar file. The API is documented as below:
download_pojo(model, path=u'', get_jar=True)
Download the POJO for this model to the directory specified by the path; if the path is "", then dump to screen.
:param model: the model whose scoring POJO should be retrieved.
:param path: an absolute path to the directory where POJO should be saved.
:param get_jar: retrieve the h2o-genmodel.jar also.
Once you have download POJO, you can use the above sample application to perform the scoring and make sure the POJO class name and the "modelClassName" are same along with model type.
I've recently developed a "classic" 3-tier web applications using Java EE.
I've used GlassFish as application server, MS SQL Server as DBMS and xhtml pages with primefaces components for the front end.
Now, for educational purposes, I want to substitute the relational db with a pure triplestore database but I'm not sure about the procedure to follow.
I've searched a lot on google and on this site but I didn't find what I was looking for, because every answer I found was more theoretical than practical.
If possible, I need a sort of tutorial or some practical tips.
I've read the documentation about Apache Jena but I'm not able to find a solid starting point.
In particoular:
- In order to use MS SQL Server with GlassFish I've used a JDBC Driver, created a datasource and a connection pool. Does it exist an equivalent procedure to set up a triple store database?
- To handle users authentication, I've used a Realm. What should I do now?
For the moment I've created "by hand" a RDF schema and using Jena Schemagen I've translated it into a Java Class. What should I do now?
After several attempts and other research on the net I finally achieved my goal.
I decided to develop a hybrid solution in which I manage users login and their navigation permits via MS SQL Server and JDBCRealm, while I use Jena TDB to save all the other data.
Starting with an RDF schema, I created a Java class that contains resources and properties to easily create my statements via code. Here's an example:
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
xmlns="http://www.stackoverflow.com/example#"
xml:base="http://www.stackoverflow.com/example">
<rdfs:Class rdf:ID="User"></rdfs:Class>
<rdfs:Class rdf:ID="Project"></rdfs:Class>
<rdf:Property rdf:ID="email"></rdf:Property>
<rdf:Property rdf:ID="name"></rdf:Property>
<rdf:Property rdf:ID="surname"></rdf:Property>
<rdf:Property rdf:ID="description"></rdf:Property>
<rdf:Property rdf:ID="customer"></rdf:Property>
<rdf:Property rdf:ID="insertProject">
<rdfs:domain rdf:resource="http://www.stackoverflow.com/example#User"/>
<rdfs:range rdf:resource="http://www.stackoverflow.com/example#Project"/>
</rdf:Property>
</rdf:RDF>
And this is the Java class:
public class MY_ONTOLOGY {
private static final OntModel M = ModelFactory.createOntologyModel(OntModelSpec.RDFS_MEM);
private static final String NS = "http://www.stackoverflow.com/example#";
private static final String BASE_URI = "http://www.stackoverflow.com/example/";
public static final OntClass USER = M.createClass(NS + "User");
public static final OntClass PROJECT = M.createClass(NS + "Project");
public static final OntProperty EMAIL = M.createOntProperty(NS + "hasEmail");
public static final OntProperty NAME = M.createOntProperty(NS + "hasName");
public static final OntProperty SURNAME = M.createOntProperty(NS + "hasSurname");
public static final OntProperty DESCRIPTION = M.createOntProperty(NS + "hasDescription");
public static final OntProperty CUSTOMER = M.createOntProperty(NS + "hasCustomer");
public static final OntProperty INSERTS_PROJECT = M.createOntProperty(NS + "insertsProject");
public static final String getBaseURI() {
return BASE_URI;
}
}
Then I've created a directory on my PC where I want to store the data, like C:\MyTDBdataset.
To store data inside it, I use the following code:
String directory = "C:\\MyTDBdataset";
Dataset dataset = TDBFactory.createDataset(directory);
dataset.begin(ReadWrite.WRITE);
try {
Model m = dataset.getDefaultModel();
Resource user = m.createResource(MY_ONTOLOGY.getBaseURI() + "Ronnie", MY_ONTOLOGY.USER);
user.addProperty(MY_ONTOLOGY.NAME, "Ronald");
user.addProperty(MY_ONTOLOGY.SURNNAME, "Red");
user.addProperty(MY_ONTOLOGY.EMAIL, "ronnie#myemail.com");
Resource project = m.createResource(MY_ONTOLOGY.getBaseURI() + "MyProject", MY_ONTOLOGY.PROJECT);
project.addProperty(MY_ONTOLOGY.DESCRIPTION, "This project is fantastic");
project.addProperty(MY_ONTOLOGY.CUSTOMER, "Customer & Co");
m.add(user, MY_ONTOLOGY.INSERTS_PROJECT, project);
dataset.commit();
} finally {
dataset.end();
}
If I want to read statements in my TDB, I can use something like this:
dataset.begin(ReadWrite.READ);
try {
Model m = dataset.getDefaultModel();
StmtIterator iter = m.listStatements();
while (iter.hasNext()) {
Statement stmt = iter.nextStatement();
Resource subject = stmt.getSubject();
Property predicate = stmt.getPredicate();
RDFNode object = stmt.getObject();
System.out.println(subject);
System.out.println("\t" + predicate);
System.out.println("\t\t" + object);
System.out.println("");
}
m.write(System.out, "RDF/XML"); //IF YOU WANT TO SEE AT CONSOLE YOUR DATA AS RDF/XML
} finally {
dataset.end();
}
If you want to navigate your model in different ways, look at this tutorial provided by Apache.
If you want to remove specific statements in your model, you can write something like this:
dataset.begin(ReadWrite.WRITE);
try {
Model m = dataset.getDefaultModel();
m.remove(m.createResource("http://http://www.stackoverflow.com/example/Ronnie"), MY_ONTOLOGY.NAME, m.createLiteral("Ronald"));
dataset.commit();
} finally {
dataset.end();
}
That's all! Bye!
I need to create RDF/XML documents containing objects in the OSLC namespace.
e.g.
<oslc_disc:ServiceProviderCatalog
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:dc="http://purl.org/dc/terms/"
xmlns:oslc_disc="http://open-services.net/xmlns/discovery/1.0/"
rdf:about="{self}">
<dc:title>{catalog title}</dc:title>
<oslc_disc:details rdf:resource="{catalog details uri}" />
what is the simplest way to create this doc using the Jena API ?
( I know about Lyo, they use a JSP for this doc :-)
Thanks, Carsten
Here's a complete example to start you off. Be aware that this will be equivalent to XML output you want, but may not be identical. The order of properties, for example, may vary, and there are other ways to write the same content.
import com.hp.hpl.jena.rdf.model.*
import com.hp.hpl.jena.vocabulary.DCTerms;
public class Jena {
// Vocab items -- could use schemagen to generate a class for this
final static String OSLC_DISC_NS = "http://open-services.net/xmlns/discovery/1.0/";
final static Resource ServiceProviderCatalog =
ResourceFactory.createResource(OSLC_DISC_NS + "ServiceProviderCatalog");
final static Property details =
ResourceFactory.createProperty(OSLC_DISC_NS, "details");
public static void main(String[] args) {
// Inputs
String selfURI = "http://example.com/self";
String catalogTitle = "Catalog title";
String catalogDetailsURI = "http://example.com/catalogDetailsURI";
// Create in memory model
Model model = ModelFactory.createDefaultModel();
// Set prefixes
model.setNsPrefix("dc", DCTerms.NS);
model.setNsPrefix("oslc_disc", OSLC_DISC_NS);
// Add item of type spcatalog
Resource self = model.createResource(selfURI, ServiceProviderCatalog);
// Add the title
self.addProperty(DCTerms.title, catalogTitle);
// Add details, which points to a resource
self.addProperty(details, model.createResource(catalogDetailsURI));
// Write pretty RDF/XML
model.write(System.out, "RDF/XML-ABBREV");
}
}
I want to insert data in my ontology using this code:
Resource resource = model.createResource(X_NAMESPACE + Global_ID);
Property prop = model.createProperty(RDF_NAMESPACE + "type");
Resource obj = model.createResource(X_NAMESPACE + "X");
model.add(resource, prop, obj);
First, does this code correctly create an individual of the specified type?
When I run this code, it saves without a problem, and the model looks correct, but when I want to query the model, I had problems. For example, I save some data in X, and when I retrieve it, all other data is retrieved.
Your code for creating a resource is correct, but it's not very idiomatic. There are methods provided by the Model interface that will make creating resources easier, and there are methods in the Resource interface that will make adding types easier too. Heres' code that illustrates these:
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.vocabulary.RDF;
public class CreateResourceExample {
public static void main(String[] args) {
Model model = ModelFactory.createDefaultModel();
String NS = "http://stackoverflow.com/q/22471651/1281433/";
model.setNsPrefix( "", NS );
// Create the class resource
Resource thing = model.createResource( NS+"ThingA" );
// The model API provides methods for creating resources
// of specified types.
Resource x = model.createResource( NS+"X", thing );
// If you want to create the triples manually, you can
// use the predefined vocabulary classes.
Resource y = model.createResource( NS+"Y" );
model.add( y, RDF.type, thing );
// You can also use the Resource API to add properties
Resource z = model.createResource( NS+"Z" );
z.addProperty( RDF.type, thing );
// Show the model
model.write( System.out, "TTL" );
}
}