Code to create an individual in an ontology? - java

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" );
}
}

Related

How to consume a H2OModel computed and saved in Python API

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.

how to create OSLC docs using Jena?

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");
}
}

Java: Ways for source code autocompletion on netbeans having external source

First of all, I'm not sure about if the title or the tags are correct. If not, someone please correct me
My question is if there are any tools or ways to create an autocomplete list with items from an external source, having netbeans parsing it and warn me if there are any errors.
-- The problem: I use JDBC and I want to model somehow all my schemas, tables and columns so that netbeans can parse it and warn me if I have anything wrong. For example with a normal use of JDBC I would had a function:
ResultSet execSelect( String cols, String table ){
return statement.executeQuery("SELECT "+cols+" FROM "+table); }
The problem is that someone should know exactly what are the available params for that to pass the correct strings.
I would like netbeans to show me somehow an autocomplete list with all available options.
PS. I had exactly the same problem when I was building a web application and I wanted somehow to get all paths for my external resources like images, .js files, .css files etc.
-- Thoughts so far:
My thoughts till now were to put a .java file with public static final String vars with some how nested static classes so that I could access from anywhere. For example:
DatabaseModel.MySchema.TableName1.ColumnName2
would be a String varialble with the 'ColumnName2' column and 'TableName1' table. That would help me with autocompletes but the problem is that there is no type checking. In other words someone could use any string, global defined or not as a table and as a column which is not correct either. I'm thinking to use nested enums somehow to cover these cases about type checking but I'm not sure if that would be a good solution in any case.
Any thoughts?
Finally I came up with writting a "script" that connects to mysql gets all meta data (every column of every table of every schema) and creates a java file with predefined classes and Strings that describes the model. For example:
- If you want the name of the column C1 from table T1 from schema S1 you would type DatabaseModel.S1.T1.C1._ which is a public static final String with the column name.
- If you want the table T2 from schema S2 you would type DatabaseModel.S2.T2 which is a class that implements DatabaseTable interface. So the function: execSelect could take a DatabaseTable and a DatabaseColumn as a parameter.
Here is the code (not tested but the idea is clear I think).
public static void generateMysqlModel(String outputFile) throws IOException, SQLException{
//** Gather the database model
// Maps a schema -> table -> column
HashMap<String,HashMap<String,ArrayList<String>>> model =
new HashMap<String,HashMap<String,ArrayList<String>>>();
openDatabase();
Connection sqlConn = DriverManager.getConnection(url, username, password);
DatabaseMetaData md = sqlConn.getMetaData();
ResultSet schemas = md.getSchemas(); // Get schemas
while( schemas.next() ){ // For every schema
String schemaName = schemas.getString(1);
model.put( schemaName, new HashMap<String,ArrayList<String>>() );
ResultSet tables = md.getTables(null, null, "%", null); // Get tables
while (tables.next()) { // For every table
String tableName = tables.getString(3);
model.get(schemaName).put( tableName, new ArrayList<String>() );
// Get columns for table
Statement s = sqlConn.createStatement(); // Get columns
s.execute("show columns in "+tables.getString(3)+";");
ResultSet columns = s.getResultSet();
while( columns.next() ){ // For every column
String columnName = columns.getString(1);
model.get(schemaName).get(tableName).add( columnName );
}
}
}
closeDatabase();
//** Create the java file from the collected model
new File(outputFile).createNewFile();
BufferedWriter bw = new BufferedWriter( new FileWriter(outputFile) ) ;
bw.append( "public class DatabaseModel{\n" );
bw.append( "\tpublic interface DatabaseSchema{};\n" );
bw.append( "\tpublic interface DatabaseTable{};\n" );
bw.append( "\tpublic interface DatabaseColumn{};\n\n" );
for( String schema : model.keySet() ){
HashMap<String,ArrayList<String>> schemaTables = model.get(schema);
bw.append( "\tpublic static final class "+schema+" implements DatabaseSchema{\n" );
//bw.append( "\t\tpublic static final String _ = \""+schema+"\";\n" );
for( String table : schemaTables.keySet() ){
System.out.println(table);
ArrayList<String> tableColumns = schemaTables.get(table);
bw.append( "\t\tpublic static final class "+table+" implements DatabaseTable{\n" );
//bw.append( "\t\t\tpublic static final String _ = \""+table+"\";\n" );
for( String column : tableColumns ){
System.out.println("\t"+column);
bw.append( "\t\t\tpublic static final class "+column+" implements DatabaseColumn{"
+ " public static final String _ = \""+column+"\";\n"
+ "}\n" );
}
bw.append( "\t\t\tpublic static String val(){ return this.toString(); }" );
bw.append( "\t\t}\n" );
}
bw.append( "\t\tpublic static String val(){ return this.toString(); }" );
bw.append( "\t}\n" );
}
bw.append( "}\n" );
bw.close();
}
PS. For the resources case in a web application I guess someone could get all files recursively from the "resources" folder and fill in the model variable. That will create a java file with the file paths. The interfaces in that case could be the file types or any other "file view" you want.
I also thought that it would be useful to create the .java file from an XML file for any case, so anyone would just create some kind of defintion in an xml file for that purpose.
If someone implements anything like that can post it here.
Any comments/improvements will be welcomed.

Calling a method from inside StreamingMarkupBuilder

I'm using Groovy's StreamingMarkupBuilder to generate XML dynamically based on the results of a few SQL queries. I'd like to call a method from inside of the closure but the markup builder tries to create an XML node using the method name.
Here's an example of what I'm trying to do:
Map generateMapFromRow(GroovyRowResult row) {
def map = [:]
def meta = row.getMetaData()
// Dynamically generate the keys and values
(1..meta.getColumnCount()).each { column -> map[meta.getColumnName(column)] = row[column-1] }
return map
}
def sql = Sql.newInstance(db.url, db.user, db.password, db.driver)
def builder = new StreamingMarkupBuilder()
def studentsImport = {
students {
sql.eachRow('select first_name, middle_name, last_name from students') { row ->
def map = generateMapFromRow(row) // Here is the problem line
student(map)
}
}
}
println builder.bind(studentsImport).toString()
This will generate XML similar to the following:
<students>
<generateMapFromRow>
[first_name:Ima, middle_name:Good, last_name:Student]
</generateMapFromRow>
<student/>
<generateMapFromRow>
[first_name:Ima, middle_name:Bad, last_name:Student]
</generateMapFromRow>
<student/>
</students>
I've tried moving the method out to a class and calling to statically on the class, which doesn't work also.
Due to the nature of how StreamingMarkupBuilder works, I'm afraid that it isn't actually possible to do this, but I'm hoping that it is.
I may loose smth during example simplification, but such code will work.
In your example students is a closure call, so it may mess smth inside.
def builder = new groovy.xml.StreamingMarkupBuilder()
def generateMapFromRow = { ["$it": it] }
builder.bind {
10.times {
def map = generateMapFromRow(it) // Now closure is escaped, there is local variable with such name.
student(map)
}
}
As said here: http://groovy.codehaus.org/Using+MarkupBuilder+for+Agile+XML+creation
Things to be careful about when using markup builders is not to overlap variables you currently have in scope. The following is a good example
import groovy.xml.MarkupBuilder
def book = "MyBook"
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
xml.shelf() {
book(name:"Fight Club") { // Will produce error.
}
}
println writer.toString()
Builder's work similar to MethodMissing captors, ans if there is local variable in scope, no node will be produced.

JENA RDF/XML format rdfs example

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" );
}

Categories