KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > hp > hpl > jena > reasoner > rdfsReasoner1 > BRWRule


1 /******************************************************************
2  * File: BRWRule.java
3  * Created by: Dave Reynolds
4  * Created on: 22-Jan-2003
5  *
6  * (c) Copyright 2003, 2004, 2005 Hewlett-Packard Development Company, LP
7  * [See end of file]
8  * $Id: BRWRule.java,v 1.10 2005/02/21 12:16:35 andy_seaborne Exp $
9  *****************************************************************/

10 package com.hp.hpl.jena.reasoner.rdfsReasoner1;
11
12 import com.hp.hpl.jena.reasoner.*;
13 import com.hp.hpl.jena.graph.*;
14 import com.hp.hpl.jena.vocabulary.*;
15 import com.hp.hpl.jena.util.iterator.*;
16
17 import java.util.*;
18
19 /**
20  * Datastructure to hold a trivial backward rewrite rule.
21  *
22  * <p>The rules take the form "pattern &lt;- pattern" where the pattern
23  * is is a triple pattern with variables. The head pattern uses the
24  * variables s/p/o to refer to the subject/predicate/object parts of the
25  * body pattern. Similarly, the body pattern uses s/p/o to refer to
26  * the corresponding parts of the query being processed.</p>
27  *
28  * @author <a HREF="mailto:der@hplb.hpl.hp.com">Dave Reynolds</a>
29  * @version $Revision: 1.10 $ on $Date: 2005/02/21 12:16:35 $
30  */

31 public class BRWRule {
32
33     /** The head of the rule */
34     protected TriplePattern head;
35     
36     /** The body of the rule */
37     protected TriplePattern body;
38     
39     
40     /**
41      * Constructor
42      */

43     public BRWRule(TriplePattern head, TriplePattern body) {
44         this.head = head;
45         this.body = body;
46     }
47     
48     /**
49      * Factory method that builds a rule instance by parsing
50      * a simple string representation of the form:
51      * <pre>
52      * ?s prop foo <- ?a ns:prop _
53      * </pre>
54      * Variables are either _ or ?x, uri's are either simple strings (no spaces)
55      * or qnames. The prefix in qnames are restricted to rdf and rdfs.
56      * Minimal error checking.
57      */

58     public static BRWRule makeRule(String JavaDoc rulespec) {
59         StringTokenizer tokenizer = new StringTokenizer(rulespec);
60         try {
61             Node headS = parseNode(tokenizer.nextToken());
62             Node headP = parseNode(tokenizer.nextToken());
63             Node headO = parseNode(tokenizer.nextToken());
64             TriplePattern head = new TriplePattern(headS, headP, headO);
65             if (!tokenizer.nextToken().equals("<-"))
66                 throw new NoSuchElementException();
67             Node bodyS = parseNode(tokenizer.nextToken());
68             Node bodyP = parseNode(tokenizer.nextToken());
69             Node bodyO = parseNode(tokenizer.nextToken());
70             TriplePattern body = new TriplePattern(bodyS, bodyP, bodyO);
71             return new BRWRule(head, body);
72         } catch (NoSuchElementException e) {
73             throw new ReasonerException("Illegal BRWRule: " + rulespec);
74         }
75     }
76     
77     /**
78      * Use the rule to implement the given query. This will
79      * instantiate the rule against the query, run the new query
80      * against the whole reasoner+rawdata again and then rewrite the
81      * results from that query according the rule.
82      * @param query the query being processed
83      * @param infGraph the parent infGraph that invoked us, will be called recursively
84      * @param data the raw data graph which gets passed back to the reasoner as part of the recursive invocation
85      * @param firedRules set of rules which have already been fired and should now be blocked
86      * @return a ExtendedIterator which aggregates the matches and rewrites them
87      * according to the rule
88      */

89     public ExtendedIterator execute(TriplePattern query, InfGraph infGraph, Finder data, HashSet firedRules) {
90         TriplePattern iBody = instantiate(body, query);
91         BRWRule iRule = new BRWRule(head, iBody);
92         if (firedRules.contains(iRule)) {
93             // No additional answers to be found
94
return NullIterator.instance;
95         }
96         firedRules.add(iRule);
97         Iterator it = ((RDFSInfGraph) infGraph).findNested(iBody, data, firedRules);
98         firedRules.remove(iRule);
99         return new RewriteIterator(it, iRule);
100     }
101
102     /**
103      * Return true if this rule is a a complete solution to the given
104      * query and the router need look no further
105      */

106     public boolean completeFor(TriplePattern query) {
107         return false;
108     }
109     
110     /**
111      * instantiate a triple pattern against a query/value
112      */

113     protected static TriplePattern instantiate(TriplePattern pattern, TriplePattern query) {
114         return new TriplePattern( instantiate(pattern.getSubject(), query),
115                                    instantiate(pattern.getPredicate(), query),
116                                    instantiate(pattern.getObject(), query) );
117     }
118
119     /**
120      * instantiate a rule body element against a query
121      */

122     protected static Node instantiate(Node elt, TriplePattern query) {
123         if (elt.isVariable()) {
124             String JavaDoc var = elt.getName(); // interned so can use simple equality test
125
if (var.equals("s")) return query.getSubject();
126             if (var.equals("p")) return query.getPredicate();
127             if (var.equals("o")) return query.getObject();
128         }
129         return elt;
130     }
131     
132     /**
133      * instantiate a rule body element against a query ground value
134      */

135     protected static Node instantiate(Node elt, Triple value) {
136         if (elt.isVariable()) {
137             String JavaDoc var = elt.getName(); // interned so can use simple equality test
138
if (var.equals("s")) return value.getSubject();
139             if (var.equals("p")) return value.getPredicate();
140             if (var.equals("o")) return value.getObject();
141         }
142         return elt;
143     }
144
145     /**
146      * Assistant method to makeRule than parses a token as a node.
147      */

148     public static Node parseNode(String JavaDoc token) {
149         if (token.startsWith("?")) {
150             return Node.createVariable(token.substring(1));
151         } else if (token.equals("_")) {
152             return Node.createVariable("*");
153         } else if (token.indexOf(':') != -1) {
154             int split = token.indexOf(':');
155             String JavaDoc nsPrefix = token.substring(0, split);
156             String JavaDoc localname = token.substring(split+1);
157             if (nsPrefix.equalsIgnoreCase("rdf")) {
158                 return Node.createURI(RDF.getURI() + localname);
159             } else if (nsPrefix.equalsIgnoreCase("rdfs")) {
160                 return Node.createURI(RDFS.getURI() + localname);
161             } else {
162                 return Node.createURI(token);
163             }
164         } else {
165             return Node.createURI(token);
166         }
167     }
168     
169     /**
170      * Printable string form
171      */

172     public String JavaDoc toString() {
173         return head.toString() + " <- " + body.toString();
174     }
175     
176         
177     /**
178      * Returns the body.
179      * @return TriplePattern
180      */

181     public TriplePattern getBody() {
182         return body;
183     }
184
185     /**
186      * Returns the head.
187      * @return TriplePattern
188      */

189     public TriplePattern getHead() {
190         return head;
191     }
192     
193     /** Equality override */
194     public boolean equals(Object JavaDoc o) {
195         return o instanceof BRWRule &&
196                 head.equals(((BRWRule)o).head) &&
197                 body.equals(((BRWRule)o).body) ;
198     }
199         
200     /** hash function override */
201     public int hashCode() {
202         return (head.hashCode() >> 1) ^ body.hashCode();
203     }
204
205     /**
206      * Inner class. This implements an iterator that uses the rule to rewrite any
207      * results from the supplied iterator according to the rule.
208      */

209     static class RewriteIterator extends WrappedIterator {
210         /** The head of the rewrite rule */
211         TriplePattern head;
212         
213         /**
214          * Constructor
215          * @param underlying the iterator whose results are to be rewritten
216          * @param rule the BRWRule which defines the rewrite
217          */

218         public RewriteIterator(Iterator underlying, BRWRule rule) {
219             super(underlying);
220             this.head = rule.head;
221         }
222     
223         /**
224          * @see Iterator#next()
225          */

226         public Object JavaDoc next() {
227             Triple value = (Triple)super.next();
228             return new Triple( instantiate(head.getSubject(), value),
229                                 instantiate(head.getPredicate(), value),
230                                 instantiate(head.getObject(), value) );
231         }
232     }
233
234 }
235
236 /*
237     (c) Copyright 2003, 2004, 2005 Hewlett-Packard Development Company, LP
238     All rights reserved.
239
240     Redistribution and use in source and binary forms, with or without
241     modification, are permitted provided that the following conditions
242     are met:
243
244     1. Redistributions of source code must retain the above copyright
245        notice, this list of conditions and the following disclaimer.
246
247     2. Redistributions in binary form must reproduce the above copyright
248        notice, this list of conditions and the following disclaimer in the
249        documentation and/or other materials provided with the distribution.
250
251     3. The name of the author may not be used to endorse or promote products
252        derived from this software without specific prior written permission.
253
254     THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
255     IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
256     OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
257     IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
258     INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
259     NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
260     DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
261     THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
262     (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
263     THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
264 */

265
Popular Tags