|
I've just started a project where I'm using the Sesame libraries to do some SemWebbery. I was looking for a good way to declare a method that takes two URIs and an Object, returning a Statement with the object declared to be either a Resource or a properly-typed Literal:
The tricky part, of course, is figuring out whether that 'obj' is a valid URI or a valid type of Literal. It seems that the most straightforward approach is to do something like:
However, that's a lot of typing. Does Sesame have something akin to Jena's TypeMapper class? Or maybe a method call that does some behind-the-scenes magic? |
|
I think what you want is the ValueFactory:
1
Valuefactory.createLiteral doesn't take an Object argument, so your code doesn't compile. If you do it this way you need to cast the obj to one of the overloaded types first, which requires a whole lot of additional "else if (obj instanceof ...)" code blocks 1
@Gerrit V, good point, hadn't thought of that. Feature request logged. https://openrdf.atlassian.net/browse/SES-1671 . Should be trivial. Appreciate the feature request! For now, though, we have enough control over literal values coming into the system (ie nobody's passing a java.io.File object into that position) that I can just call result= ValueFactory.createLiteral(obj.toString()). |
|
Starting from Sesame-2.7.0 you can also solve the issue with the new DatatypeHandler interface, either extending the default XMLSchemaDatatypeHandler or replacing it with your own. To implement the replacement you need to use ParserConfig to tell the Parser's and RepositoryConnection's what to use:
Inside of DatatypeHandler.normalizeLiteral you can create the Literal using any method you want, including not using the given ValueFactory if necessary. By the way, Jeen's idea for ValueFactory.createLiteral(Object) was migrated to a new helper method as Literals.createLiteral(ValueFactory, Object) method in the final 2.7.0 release. Having a ValueFactory.createLiteral(Object) method may have hampered our ability to add to the interface in future. The Literals method will resort to using obj.toString if the datatype is unknown, but you can also using Literals.createLiteralOrFail if you wish to fail instead of using obj.toString as a backup. |


Is it possible that the object be a blank node in your case?
No, fortunately the data we're using are either URIs or literals. But you're right - a more robust sol'n would distinguish URIs and blank nodes. In fact, the longer I stare at that section of the code, the more I think I just might put that change in :)