Yes, recursion makes perfect sense.

Now why didn't I think of it?

Thanks Andy.


On Fri, Oct 21, 2016 at 1:26 PM, Andy Seaborne <[email protected]> wrote:

> Hi Nikolaos,
>
> It is possible to call the path evaluator directly, see PathLib.   You can
> buld paths programmatically using PathFactory.
>
> There is a parser for paths written in algebra syntax SSE.parsePath (print
> out a few SPARQL queries with paths to get the syntax).
>
> If you want to search for possibilities (maybe only some choices have a
> long enough path, maybe multiple matches) then SPARQL or other means and
> calling the path evaluator is probably easier.
>
> If the paths are always a fixed shape and length, some recursive code can
> be enough: (untested):
>
> public static RDFNode access(Resource r, List<Property> properties) {
>     if ( properties.isEmpty() )
>         return null ;
>     return access(r, 0, properties) ;
> }
>
> private static RDFNode access(Resource r, int idx,
>                              List<Property> properties) {
>     Property p = properties.get(idx) ;
>     RDFNode n = r.getProperty(p).getObject() ;
>     if ( idx+1 == properties.size() )
>         return n ;
>     if ( n == null )
>         return null ;
>     if ( ! n.isResource() )
>         return null ;
>     return access(n.asResource(), idx, properties) ;
> }
>
> See also getRequiredProperty if you want exceptions not nulls.
>
>     Andy
>
>
>
>
> On 20/10/16 12:47, Nikolaos Beredimas wrote:
>
>> I have written code that looks like this:
>>
>> Property myPropertyA = ...
>> Property myPropertyB = ...
>> Property myPropertyC = ...
>> Model model = ...
>> NodeIterator iterA, iterB, iterC;
>> RDFNode nodeA, nodeB, nodeC;
>>
>> if (                  (iterA =
>> model.listObjectsOfProperty(myPropertyA)).hasNext()
>>                 && (nodeA = iterA.next()).isResource()
>>                 && (iterB =
>> model.listObjectsOfProperty(nodeA.asResource(), myPropertyB)).hasNext()
>>                 && (nodeB = iterB.next()).isResource()
>>                 && (iterC =
>> model.listObjectsOfProperty(nodeB.asResource(), myPropertyC)).hasNext()
>>                 && (nodeC = iterC.next()).isLiteral()) {
>>             String toReturn = nodeC.asLiteral().getString();
>>         }
>>
>> Essentially I'm trying to get the first literal (if it exists) value for a
>> property path like
>> :Resource_1 :myPropertyA/:myPropertyB/:myPropertyC "literal"
>>
>> Is there a better (but non SPARQL) way of achieving this? Maybe some
>> method
>> that I overlooked?
>>
>> Because although the above code pattern works, it's not easily expandable.
>> I would hate to see what it would look like if I were not searching for
>> the
>> first value, but for all values.
>>
>>

Reply via email to