BRWRule.java
上传用户:rxy7129985
上传日期:2016-10-30
资源大小:21750k
文件大小:10k
源码类别:

Java编程

开发平台:

Java

  1. /******************************************************************
  2.  * File:        BRWRule.java
  3.  * Created by:  Dave Reynolds
  4.  * Created on:  22-Jan-2003
  5.  * 
  6.  * (c) Copyright 2003, 2004, 2005, 2006, 2007 Hewlett-Packard Development Company, LP
  7.  * [See end of file]
  8.  * $Id: BRWRule.java,v 1.12 2007/01/02 11:48:52 andy_seaborne Exp $
  9.  *****************************************************************/
  10. package com.hp.hpl.jena.reasoner.rdfsReasoner1;
  11. import com.hp.hpl.jena.reasoner.*;
  12. import com.hp.hpl.jena.graph.*;
  13. import com.hp.hpl.jena.vocabulary.*;
  14. import com.hp.hpl.jena.util.iterator.*;
  15. import java.util.*;
  16. /**
  17.  * Datastructure to hold a trivial backward rewrite rule.
  18.  * 
  19.  * <p>The rules take the form "pattern &lt;- pattern" where the pattern
  20.  * is is a triple pattern with variables. The head pattern uses the
  21.  * variables s/p/o to refer to the subject/predicate/object parts of the
  22.  * body pattern. Similarly, the body pattern uses s/p/o to refer to
  23.  * the corresponding parts of the query being processed.</p>
  24.  * 
  25.  * @author <a href="mailto:der@hplb.hpl.hp.com">Dave Reynolds</a>
  26.  * @version $Revision: 1.12 $ on $Date: 2007/01/02 11:48:52 $
  27.  */
  28. public class BRWRule {
  29.     /** The head of the rule */
  30.     protected TriplePattern head;
  31.     
  32.     /** The body of the rule */
  33.     protected TriplePattern body;
  34.     
  35.     
  36.     /**
  37.      * Constructor
  38.      */
  39.     public BRWRule(TriplePattern head, TriplePattern body) {
  40.         this.head = head;
  41.         this.body = body;
  42.     }
  43.     
  44.     /**
  45.      * Factory method that builds a rule instance by parsing
  46.      * a simple string representation of the form:
  47.      * <pre>
  48.      *   ?s prop foo <- ?a ns:prop _ 
  49.      * </pre>
  50.      * Variables are either _ or ?x, uri's are either simple strings (no spaces)
  51.      * or qnames. The prefix in qnames are restricted to rdf and rdfs.
  52.      * Minimal error checking.
  53.      */
  54.     public static BRWRule makeRule(String rulespec) {
  55.         StringTokenizer tokenizer = new StringTokenizer(rulespec);
  56.         try {
  57.             Node headS = parseNode(tokenizer.nextToken());
  58.             Node headP = parseNode(tokenizer.nextToken());
  59.             Node headO = parseNode(tokenizer.nextToken());
  60.             TriplePattern head = new TriplePattern(headS, headP, headO);
  61.             if (!tokenizer.nextToken().equals("<-"))
  62.                 throw new NoSuchElementException();
  63.             Node bodyS = parseNode(tokenizer.nextToken());
  64.             Node bodyP = parseNode(tokenizer.nextToken());
  65.             Node bodyO = parseNode(tokenizer.nextToken());
  66.             TriplePattern body = new TriplePattern(bodyS, bodyP, bodyO);
  67.             return new BRWRule(head, body);
  68.         } catch (NoSuchElementException e) {
  69.             throw new ReasonerException("Illegal BRWRule: " + rulespec);
  70.         }
  71.     }
  72.     
  73.     /**
  74.      * Use the rule to implement the given query. This will
  75.      * instantiate the rule against the query, run the new query
  76.      * against the whole reasoner+rawdata again and then rewrite the
  77.      * results from that query according the rule.
  78.      * @param query the query being processed
  79.      * @param infGraph the parent infGraph that invoked us, will be called recursively
  80.      * @param data the raw data graph which gets passed back to the reasoner as part of the recursive invocation
  81.      * @param firedRules set of rules which have already been fired and should now be blocked
  82.      * @return a ExtendedIterator which aggregates the matches and rewrites them
  83.      * according to the rule
  84.      */
  85.     public ExtendedIterator execute(TriplePattern query, InfGraph infGraph, Finder data, HashSet firedRules) {
  86.         TriplePattern iBody = instantiate(body, query);
  87.         BRWRule iRule = new BRWRule(head, iBody);
  88.         if (firedRules.contains(iRule)) {
  89.             // No additional answers to be found
  90.             return NullIterator.instance;
  91.         } 
  92.         firedRules.add(iRule);
  93.         Iterator it = ((RDFSInfGraph) infGraph).findNested(iBody, data, firedRules);
  94.         firedRules.remove(iRule);
  95.         return new RewriteIterator(it, iRule);
  96.     }    
  97.     /**
  98.      * Return true if this rule is a a complete solution to the given
  99.      * query and the router need look no further
  100.      */
  101.     public boolean completeFor(TriplePattern query) {
  102.         return false;
  103.     }
  104.     
  105.     /**
  106.      * instantiate a triple pattern against a query/value
  107.      */
  108.     protected static TriplePattern instantiate(TriplePattern pattern, TriplePattern query) {
  109.         return new TriplePattern( instantiate(pattern.getSubject(), query),
  110.                                    instantiate(pattern.getPredicate(), query),
  111.                                    instantiate(pattern.getObject(), query) );
  112.     }
  113.     /**
  114.      * instantiate a rule body element against a query
  115.      */
  116.     protected static Node instantiate(Node elt, TriplePattern query) {
  117.         if (elt.isVariable()) {
  118.             String var = elt.getName();     // interned so can use simple equality test
  119.             if (var.equals("s")) return query.getSubject();
  120.             if (var.equals("p")) return query.getPredicate();
  121.             if (var.equals("o")) return query.getObject();
  122.         }
  123.         return elt;
  124.     }
  125.     
  126.     /**
  127.      * instantiate a rule body element against a query ground value
  128.      */
  129.     protected static Node instantiate(Node elt, Triple value) {
  130.         if (elt.isVariable()) {
  131.             String var = elt.getName();     // interned so can use simple equality test
  132.             if (var.equals("s")) return value.getSubject();
  133.             if (var.equals("p")) return value.getPredicate();
  134.             if (var.equals("o")) return value.getObject();
  135.         }
  136.         return elt;
  137.     }
  138.     /**
  139.      * Assistant method to makeRule than parses a token as a node.
  140.      */
  141.     public static Node parseNode(String token) {
  142.         if (token.startsWith("?")) {
  143.             return Node.createVariable(token.substring(1));
  144.         } else if (token.equals("_")) {
  145.             return Node.createVariable("*");
  146.         } else if (token.indexOf(':') != -1) {
  147.             int split = token.indexOf(':');
  148.             String nsPrefix = token.substring(0, split);
  149.             String localname = token.substring(split+1);
  150.             if (nsPrefix.equalsIgnoreCase("rdf")) {
  151.                 return Node.createURI(RDF.getURI() + localname);
  152.             } else if (nsPrefix.equalsIgnoreCase("rdfs")) {
  153.                 return Node.createURI(RDFS.getURI() + localname);
  154.             } else {
  155.                 return Node.createURI(token);
  156.             }
  157.         } else {
  158.             return Node.createURI(token);
  159.         }
  160.     }
  161.     
  162.     /**
  163.      * Printable string form
  164.      */
  165.     public String toString() {
  166.         return head.toString() + " <- " + body.toString();
  167.     }
  168.     
  169.         
  170.     /**
  171.      * Returns the body.
  172.      * @return TriplePattern
  173.      */
  174.     public TriplePattern getBody() {
  175.         return body;
  176.     }
  177.     /**
  178.      * Returns the head.
  179.      * @return TriplePattern
  180.      */
  181.     public TriplePattern getHead() {
  182.         return head;
  183.     }
  184.     
  185.     /** Equality override */
  186.     public boolean equals(Object o) {
  187.         return o instanceof BRWRule && 
  188.                 head.equals(((BRWRule)o).head) &&
  189.                 body.equals(((BRWRule)o).body) ;
  190.     }
  191.         
  192.     /** hash function override */
  193.     public int hashCode() {
  194.         return (head.hashCode() >> 1) ^ body.hashCode();
  195.     }
  196.     /**
  197.      * Inner class. This implements an iterator that uses the rule to rewrite any
  198.      * results from the supplied iterator according to the rule.
  199.      */
  200.     static class RewriteIterator extends WrappedIterator {
  201.         /** The head of the rewrite rule */
  202.         TriplePattern head;
  203.         
  204.         /** 
  205.          * Constructor 
  206.          * @param underlying the iterator whose results are to be rewritten
  207.          * @param rule the BRWRule which defines the rewrite
  208.          */
  209.         public RewriteIterator(Iterator underlying, BRWRule rule) {
  210.             super(underlying);
  211.             this.head = rule.head;
  212.         }
  213.     
  214.         /**
  215.          * @see Iterator#next()
  216.          */
  217.         public Object next() {
  218.             Triple value = (Triple)super.next();
  219.             return new Triple( instantiate(head.getSubject(), value),
  220.                                 instantiate(head.getPredicate(), value),
  221.                                 instantiate(head.getObject(), value) );
  222.         }
  223.     }    
  224. }
  225. /*
  226.     (c) Copyright 2003, 2004, 2005, 2006, 2007 Hewlett-Packard Development Company, LP
  227.     All rights reserved.
  228.     Redistribution and use in source and binary forms, with or without
  229.     modification, are permitted provided that the following conditions
  230.     are met:
  231.     1. Redistributions of source code must retain the above copyright
  232.        notice, this list of conditions and the following disclaimer.
  233.     2. Redistributions in binary form must reproduce the above copyright
  234.        notice, this list of conditions and the following disclaimer in the
  235.        documentation and/or other materials provided with the distribution.
  236.     3. The name of the author may not be used to endorse or promote products
  237.        derived from this software without specific prior written permission.
  238.     THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  239.     IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  240.     OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  241.     IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  242.     INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  243.     NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  244.     DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  245.     THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  246.     (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  247.     THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  248. */