Unable to query d2rq ttl file from Jena - jena

I am trying to query from a d2rq-generated ttl file. Following is my code snippet:
ModelD2RQ m = new ModelD2RQ("file:C:\\Users\\599782\\Downloads\\d2rq-0.8.1\\northwind.ttl");
String sparql =
"PREFIX vocab: <http://localhost:2020/resource/vocab/>" +
"select ?firstname ?lastname where{"+
"?x vocab:employees_Country 'USA'."+
"?x vocab:employees_FirstName ?firstname."+
"?x vocab:employees_LastName ?lastname."+
"}";
Query q = QueryFactory.create(sparql);
ResultSet rs = QueryExecutionFactory.create(q, m).execSelect();
ResultSetFormatter.out(System.out, rs, q);
m.close();
And it shows this exception:
Exception in thread "main" java.lang.IncompatibleClassChangeError: Class com.hp.hpl.jena.sparql.algebra.op.OpProject does not implement the requested interface org.openjena.atlas.io.Printable
at org.openjena.atlas.io.PrintUtils.toString(PrintUtils.java:28)
at de.fuberlin.wiwiss.d2rq.engine.QueryEngineD2RQ.translate(QueryEngineD2RQ.java:70)
at de.fuberlin.wiwiss.d2rq.engine.QueryEngineD2RQ.modifyOp(QueryEngineD2RQ.java:60)
at com.hp.hpl.jena.sparql.engine.QueryEngineBase.createPlan(QueryEngineBase.java:94)
at com.hp.hpl.jena.sparql.engine.QueryEngineBase.getPlan(QueryEngineBase.java:87)
at de.fuberlin.wiwiss.d2rq.engine.QueryEngineD2RQ$QueryEngineFactoryD2RQ.create(QueryEngineD2RQ.java:110)
at com.hp.hpl.jena.sparql.engine.QueryExecutionBase.getPlan(QueryExecutionBase.java:513)
at com.hp.hpl.jena.sparql.engine.QueryExecutionBase.startQueryIterator(QueryExecutionBase.java:490)
at com.hp.hpl.jena.sparql.engine.QueryExecutionBase.execResultSet(QueryExecutionBase.java:498)
at com.hp.hpl.jena.sparql.engine.QueryExecutionBase.execSelect(QueryExecutionBase.java:194)
at com.jenaproj.HelloJena.main(HelloJena.java:159)
Anyone have any idea what might be going on.

java.lang.IncompatibleClassChangeError
You have incompatible versions of the jars on your classpath.
If you use the Jena jars from d2rq they should be the correct version, otherwise you need a version of d2rq compiled against the Jena jars you wish to use.

Related

How to read a file in src/main/resources in grails

This has been asked before, and I have tried each proposed solution, but all fail.
I have put a javascript file (hl.js) in myapp/src/main/resources
I have tried to read it with the following code taken from the "solutions":
1 - getRsourcesAsStream. returns null inputstream.
InputStream is = this.class.classLoader.getResourceAsStream("hl.js")
2 - getResource - returns null
File myFile = grailsApplication.mainContext.getResource("hl.js").file
3 - getResourceAsStream with classloader - returns null.
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream is = classLoader.getResourceAsStream("hl.js");
Interestingly, if I do the following:
String fileNameAndPath = this.class.classLoader.getResource("hl.js").getFile()
System.out.println(fileNameAndPath);
File file = new File(fileNameAndPath)
InputStream is = file.newInputStream();
This prints out:
/Users/me/dev/grails_projects/myapp/src/main/resources/hl.js
But "is" is always null.
I an trying to get an input stream so I can evaluate the javascript via nashorn:
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval(is)
Grails 3.3.8
Any ideas?
Get the resource and open a stream on it.
def resource = this.class.classLoader.getResource('conf.json')
def path = resource.file // absolute file path
return resource.openStream() // input stream for the file
Source: https://www.damirscorner.com/blog/posts/20160313-AccessingApplicationFilesFromCodeInGrails.html
Well, I dont know why the solutions 1, 2 and 3 do not work, but I found a more long winded way which does work. The main issue is that there are lots of different implementations of eval(), and netbeans "go to declaration" has never worked (presumably some configuration issue in netbeans).
It turns out that the eval() version i happen to be using is expecting a Reader, where as the default documentation shows it needs in InputStream. Also, reader is not the same as InputStreamReader.
This is the solution I found:
import javax.script.ScriptEngine
import javax.script.ScriptEngineManager
import org.grails.core.io.ResourceLocator
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
String fileNameAndPath = this.class.classLoader.getResource("hl.js").getFile()
System.out.println(fileNameAndPath);
File file = new File(fileNameAndPath)
System.out.println("exists: " + file.exists())
Reader reader = file.newReader();
engine.eval(reader)

Not able to access iterator() from RestTraverser, it gives exception java.lang.IllegalAccessError

I am implementing traversal framework using neo4j java-rest-binding project.
Code is as follows:
RestAPI db = new RestAPIFacade("http://localhost:7474/db/data");
RestNode n21 = db.getNodeById(21);
Map<String,Object> traversalDesc = new HashMap<String, Object>();
traversalDesc.put("order", "breadth_first");
traversalDesc.put("uniqueness", "node_global");
traversalDesc.put("uniqueness", "relationship_global");
traversalDesc.put("returnType", "fullpath");
traversalDesc.put("max_depth", 2);
RestTraverser traverser = db.traverse(n21, traversalDesc);
Iterable<Node> nodes = traverser.nodes();
System.out.println("All Nodes:"); // First Task
for(Node n:nodes){
System.out.println(n.getId());
}
Iterable<Relationship> rels = traverser.relationships();
System.out.println("All Relations:"); // Second Task
for(Relationship r:rels){
System.out.println(r.getId());
}
Iterator<Path> paths = traverser.iterator(); // Third Task
while(paths.hasNext()){
System.out.println(paths.next());
}
I need to do 3 tasks as commented in the code:
Print all the node IDs related to node no. 21
Print all the relation IDs related to node no. 21
Traverse all the paths related to node no. 21
Tasks 1 & 2 are working fine.
But when I try to do traverser.iterator() in 3rd task it throws an Exception saying:
java.lang.IllegalAccessError: tried to access class org.neo4j.helpers.collection.WrappingResourceIterator from class org.neo4j.rest.graphdb.traversal.RestTraverser
Can anyone please check why this is happening or if I am doing wrong then what is the right method to do it.
Thanks in Advance.
I don't believe using the Neo4j Traversal Framework via the REST DB binding is properly supported, nor is it advisable. If you traverse via REST, each node and each relationship will be retrieved over the network as the traversal proceeds, incurring a tremendous overhead for the traversal.
Edit: The above is not true, the REST traverser is smarter than I thought.
In general, it will be faster to use Cypher, and access the Neo4j Server using JDBC. Read more about JDBC here: https://github.com/neo4j-contrib/neo4j-jdbc
If you really want to use the Traversal Framework, you should use Server Extensions, which allow you to design a traversal to run on the server itself, and then only move the result of the traversal over the network. Read more about server extensions here: http://docs.neo4j.org/chunked/stable/server-unmanaged-extensions.html

Store data in Jena TDB and use reasoning

I have an OWL ontology file as RDF and want to store my data in a TDB and want to use reasoning. Actually this sounds simple so far :)
But here is the point where I'm confuesd:
I created a TDB an stored via SPARQL some statements. Then I tried to load the TDB via a model and OWL reasoner:
OntModelSpec ontModelSpec = OntModelSpec.OWL_MEM;
Reasoner reasoner = ReasonerRegistry.getOWLReasoner();
ontModelSpec.setReasoner(reasoner);
Model schemaModel = FileManager.get().loadModel("D:/Users/jim/Desktop/ontology/schema.rdf");
OntModel schema = ModelFactory.createOntologyModel( ontModelSpec, schemaModel);
Location location = new Location("D:/Users/jim/Desktop/jena-fuseki-0.2.5/DB");
Dataset dataset = TDBFactory.createDataset(location);
Model model = dataset.getDefaultModel();
OntModel ontModel = ModelFactory.createOntologyModel(ontModelSpec, model);
When I now create new resources via API, they are not stored in the TDB. And I'm not able to see the Statments have added via SPARQL?!
The SPAQRL statement shows me only the entries I've added with SPARQL
QueryExecution qExec = QueryExecutionFactory.create(
StrUtils.strjoinNL("SELECT ?s ?p ?prop",
"WHERE {?s ?p ?prop}"),
dataset) ;
ResultSet rs = qExec.execSelect() ;
try {
ResultSetFormatter.out(rs) ;
} finally { qExec.close() ; System.out.println("closed connection");}
and this returns only the Resource added with the API
System.out.print("instance: " + ontModel.getResource(NS + "TestItem"));
And when I call this:
ExtendedIterator<Statement> iter = ontModel.listStatements();
I get the following exception:
org.openjena.atlas.lib.InternalErrorException: Invalid id node for subject (null node): ([0000000000000067], [0000000000000093], [00000000000000C8])
Is someone able to explain that behavior? Or could someone please give me a hint how to separate schema and date with TDB in right way with using the OntModel?
Partial answer:
org.openjena.atlas.lib.InternalErrorException: Invalid id node for subject (null node): ([0000000000000067], [0000000000000093], [00000000000000C8])
You are using TDB without transactions - try adding TDB.sync before exiting to flush changes to the disk.

grails findAll() method

I am using the findAll() SQL-like method:
MyDomainClass.findAll("firstname='George' and lastname='kuo' and username='kjlop'"),
but I have got problem:
when value starts with number(for example,when age='2poj') it throws an exception
I use grails 1.3.2 and gorm-hbase 0.2.4 plugin and in my domain classes fields have String type.
Here is the Stack Trace:
expecting token in range: '0'..'9', found 'p'
at org.grails.hbase.ghql.LexerRules.nextToken(LexerRules.java:125)
at org.grails.hbase.finders.QueryStringTokenizer.tokenize(QueryStringTokenizer.groovy:59)
at org.grails.hbase.finders.TokenizerStrategy$tokenize.call(Unknown Source)
//---------
I wonder is there any way in groovy change findAll() method work ?
If anybody know solution please help.
Thanks in advance.
You should be able to run a dynamic finder method on the domain object to achieve what you need.
Example:
MyDomainClass.findAllByFirstnameAndAge('Dan', 25)
This works for all data types and enums.
You can try like the Grails example:
MyDomainClass.findAll("from DomainTable as b where b.firstname=:firstname and b.age=:age", [firstname:'Dan Brown', age: 25]
Notice: I don't know if you mistype it, but '25' is a string, so that it can't be age='25'
EDIT:
I don't know how this doesn't work, but in case you want to find with multiple properties, you should use createCriteria().
def c = MyDomainClass.createCriteria()
def results = c.list {
like("firstName", "George%")
like("age", "25");
}
EDIT2: Sorry, createCriteria is not supported by hbase plugin. Based on your condition, I think it's suitable to try DynamicFinderFilter (with approriate import).
// all books written by Dan Brown or J K Rowling
DynamicFinderFilter filterList = new FinderFilterList(Operator.OR)
DynamicFinderFilter filter1 = new Filter('author', 'Dan Brown')
filterList.addFilter(filter1)
DynamicFinderFilter filter2 = new Filter('author', 'J K Rowling')
filterList.addFilter(filter12)
results = Book.findAll(filterList)
The complete example can be find in the plugin page.

entity framework + advantage database: UDFs

I am using VS2010, Entity Framework 4.0, and Advantage v. 10 in my application. I am trying to make a UDF I have defined in my Advantage DB available to my application code. The designer does not show the UDF under stored procs in the "Update Model from Database" wizard as I would expect it to. So I manually added the UDF to the SSDL as follows:
<Function Name="Test" ReturnType="numeric" Aggregate="false" BuiltIn="false" NiladicFunction="false" IsComposable="true" ParameterTypeSemantics="AllowImplicitConversion">
<Parameter Name="PartID" Type="integer" Mode="In"/>
</Function>
I also added a CLR method stub:
[EdmFunction("namespace.Store", "Test")]
public static decimal Test(int partID)
{
throw new InvalidOperationException("Call from within an L2E query");
}
I can see the function in my Linq-to-Entities statement; however, the generated SQL is not valid. Using ToTraceString, the UDF call looks something like this:
"namespace.Store"."Test"("Project3"."PartID") AS "C4"
This gives me the following error:
System.Data.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> Advantage.Data.Provider.AdsException: Error 7200: AQE Error: State = 42000; NativeError = 2117; [iAnywhere Solutions][Advantage SQL Engine]Unexpected token: Scalar function name should not be delimited.
It works fine if I run the generated SQL in Advantage Data Architect and correct the function name like so:
Test("Project3"."PartID") AS "C4"
Is there anyway to tell Entity Framework to generate the correct SQL? Am I doing something wrong in the definition of the function in the SSDL?
Thanks in advance.
You need to change your function element to have BuiltIn="true". User Defined Functions are not quoted in the Advantage SQL grammar.
It looks good. Only thing i would recommend is to change the decimal to be nullable but i doubt that would fix the problem because then you would see a different exception. its worth a try. I do covered the function a while back.
http://weblogs.asp.net/zeeshanhirani/archive/2010/04/08/calling-user-defined-database-function-from-linq.aspx

Resources