KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jena > RuleMap


1 /******************************************************************
2  * File: RuleMap.java
3  * Created by: Dave Reynolds
4  * Created on: 04-Mar-2004
5  *
6  * (c) Copyright 2004, 2005 Hewlett-Packard Development Company, LP, all rights reserved.
7  * [See end of file]
8  * $Id: RuleMap.java,v 1.8 2005/04/11 11:29:11 der Exp $
9  *****************************************************************/

10 package jena;
11
12
13 import com.hp.hpl.jena.graph.*;
14 import com.hp.hpl.jena.rdf.model.*;
15 import com.hp.hpl.jena.reasoner.Reasoner;
16 import com.hp.hpl.jena.reasoner.rulesys.*;
17 import com.hp.hpl.jena.reasoner.rulesys.builtins.BaseBuiltin;
18 import com.hp.hpl.jena.util.FileManager;
19 import com.hp.hpl.jena.util.FileUtils;
20
21 import jena.cmdline.*;
22 import java.util.*;
23 import java.io.*;
24
25 /**
26  * General command line utility to process one RDF file into another
27  * by application of a set of forward chaining rules.
28  * <pre>
29  * Usage: RuleMap [-il inlang] [-ol outlang] [-d] rulefile infile
30  * </pre>
31  * The resulting RDF data is written to stdout in format <code>outlang</code
32  * (default N3). If <code>-d</code> is given then only the deductions
33  * generated by the rules are output. Otherwise all data including any input
34  * data (other than any removed triples) is output.
35  * <p>
36  * Rules are permitted an additional action "deduce" which forces triples
37  * to be added to the deductions graph even if they are already known (for use
38  * in deductions only mode).
39  * </p>
40  *
41  * @author <a HREF="mailto:der@hplb.hpl.hp.com">Dave Reynolds</a>
42  * @version $Revision: 1.8 $ on $Date: 2005/04/11 11:29:11 $
43  */

44 public class RuleMap {
45     
46     /**
47      * Load a set of rule definitions including processing of
48      * comment lines and any initial prefix definition lines.
49      * Also notes the prefix definitions for adding to a later inf model.
50      */

51     public static List loadRules(String JavaDoc filename, Map prefixes) throws IOException {
52         String JavaDoc fname = filename;
53         if (fname.startsWith("file:///")) {
54             fname = File.separator + fname.substring(8);
55         } else if (fname.startsWith("file:/")) {
56             fname = File.separator + fname.substring(6);
57         } else if (fname.startsWith("file:")) {
58             fname = fname.substring(5);
59         }
60
61         BufferedReader src = FileUtils.openResourceFile(fname);
62         return loadRules(src, prefixes);
63     }
64     
65     /**
66      * Load a set of rule definitions including processing of
67      * comment lines and any initial prefix definition lines.
68      * Also notes the prefix definitions for adding to a later inf model.
69      */

70     public static List loadRules(BufferedReader src, Map prefixes) throws IOException {
71         Rule.Parser parser = Rule.rulesParserFromReader(src);
72         List rules = Rule.parseRules(parser);
73         prefixes.putAll(parser.getPrefixMap());
74         return rules;
75     }
76     
77     /**
78      * Internal implementation of the "deduce" primitve.
79      * This takes the form <code> ... -> deduce(s, p, o)</code>
80      */

81     static class Deduce extends BaseBuiltin {
82
83         /**
84          * Return a name for this builtin, normally this will be the name of the
85          * functor that will be used to invoke it.
86          */

87         public String JavaDoc getName() {
88             return "deduce";
89         }
90    
91         /**
92          * Return the expected number of arguments for this functor or 0 if the number is flexible.
93          */

94         public int getArgLength() {
95             return 3;
96         }
97
98         /**
99          * This method is invoked when the builtin is called in a rule head.
100          * Such a use is only valid in a forward rule.
101          * @param args the array of argument values for the builtin, this is an array
102          * of Nodes.
103          * @param length the length of the argument list, may be less than the length of the args array
104          * for some rule engines
105          * @param context an execution context giving access to other relevant data
106          */

107         public void headAction(Node[] args, int length, RuleContext context) {
108             if (context.getGraph() instanceof FBRuleInfGraph) {
109                 Triple t = new Triple(args[0], args[1], args[2]);
110                 ((FBRuleInfGraph)context.getGraph()).addDeduction(t);
111             } else {
112                 throw new BuiltinException(this, context, "Only usable in FBrule graphs");
113             }
114         }
115     }
116     
117     /**
118      * General command line utility to process one RDF file into another
119      * by application of a set of forward chaining rules.
120      * <pre>
121      * Usage: RuleMap [-il inlang] [-ol outlang] -d infile rulefile
122      * </pre>
123      */

124     public static void main(String JavaDoc[] args) {
125         try {
126             
127             // Parse the command line
128
CommandLine cl = new CommandLine();
129             String JavaDoc usage = "Usage: RuleMap [-il inlang] [-ol outlang] [-d] rulefile infile";
130             cl.setUsage(usage);
131             cl.add("il", true);
132             cl.add("ol", true);
133             cl.add("d", false);
134             cl.process(args);
135             if (cl.items().size() != 2) {
136                 System.err.println(usage);
137                 System.exit(1);
138             }
139             
140             // Load the input data
141
Arg il = cl.getArg("il");
142             String JavaDoc inLang = (il == null) ? null : il.getValue();
143             Model inModel = FileManager.get().loadModel((String JavaDoc)cl.items().get(1), inLang);
144             
145             // Determine the type of the output
146
Arg ol = cl.getArg("ol");
147             String JavaDoc outLang = (ol == null) ? "N3" : ol.getValue();
148             
149             Arg d = cl.getArg("d");
150             boolean deductionsOnly = (d != null);
151             
152             // Fetch the rule set and create the reasoner
153
BuiltinRegistry.theRegistry.register(new Deduce());
154             Map prefixes = new HashMap();
155             List rules = loadRules((String JavaDoc)cl.items().get(0), prefixes);
156             Reasoner reasoner = new GenericRuleReasoner(rules);
157             
158             // Process
159
InfModel infModel = ModelFactory.createInfModel(reasoner, inModel);
160             infModel.prepare();
161             infModel.setNsPrefixes(prefixes);
162             
163             // Output
164
PrintWriter writer = new PrintWriter(System.out);
165             if (deductionsOnly) {
166                 Model deductions = infModel.getDeductionsModel();
167                 deductions.setNsPrefixes(prefixes);
168                 deductions.setNsPrefixes(inModel);
169                 deductions.write(writer, outLang);
170             } else {
171                 infModel.write(writer, outLang);
172             }
173             writer.close();
174             
175         } catch (Throwable JavaDoc t) {
176             System.err.println("An error occured: \n" + t);
177             t.printStackTrace();
178         }
179     }
180
181 }
182
183 /*
184     (c) Copyright 2004, 2005 Hewlett-Packard Development Company, LP
185     All rights reserved.
186
187     Redistribution and use in source and binary forms, with or without
188     modification, are permitted provided that the following conditions
189     are met:
190
191     1. Redistributions of source code must retain the above copyright
192        notice, this list of conditions and the following disclaimer.
193
194     2. Redistributions in binary form must reproduce the above copyright
195        notice, this list of conditions and the following disclaimer in the
196        documentation and/or other materials provided with the distribution.
197
198     3. The name of the author may not be used to endorse or promote products
199        derived from this software without specific prior written permission.
200
201     THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
202     IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
203     OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
204     IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
205     INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
206     NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
207     DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
208     THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
209     (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
210     THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
211 */

212
Popular Tags