KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > hp > hpl > jena > reasoner > rulesys > Util


1 /******************************************************************
2  * File: Util.java
3  * Created by: Dave Reynolds
4  * Created on: 11-Apr-2003
5  *
6  * (c) Copyright 2003, 2004, 2005 Hewlett-Packard Development Company, LP
7  * [See end of file]
8  * $Id: Util.java,v 1.24 2005/04/08 16:37:51 der Exp $
9  *****************************************************************/

10 package com.hp.hpl.jena.reasoner.rulesys;
11
12 import com.hp.hpl.jena.graph.*;
13 import com.hp.hpl.jena.graph.impl.*;
14 import com.hp.hpl.jena.rdf.model.*;
15 import com.hp.hpl.jena.reasoner.Finder;
16 import com.hp.hpl.jena.reasoner.IllegalParameterException;
17 import com.hp.hpl.jena.reasoner.TriplePattern;
18 import com.hp.hpl.jena.util.FileUtils;
19 import com.hp.hpl.jena.util.iterator.ClosableIterator;
20 import com.hp.hpl.jena.vocabulary.RDF;
21 import com.hp.hpl.jena.datatypes.xsd.XSDDateTime;
22
23 import java.io.*;
24 import java.util.*;
25
26 //Thanks to Bradley Schatz (Bradley@greystate.com) for code patches
27
//to support XSDDateTime comparisons
28

29 /**
30  * A small random collection of utility functions used by the rule systems.
31  *
32  * @author <a HREF="mailto:der@hplb.hpl.hp.com">Dave Reynolds</a>
33  * @version $Revision: 1.24 $ on $Date: 2005/04/08 16:37:51 $
34  */

35 public class Util {
36
37     /**
38      * Check whether a Node is a numeric (integer) value
39      */

40     public static boolean isNumeric(Node n) {
41         if (n.isLiteral()) {
42             Object JavaDoc o = n.getLiteral().getValue();
43             return (o instanceof Number JavaDoc);
44         } else {
45             return false;
46         }
47     }
48     
49     /**
50      * Return the integer value of a literal node
51      */

52     public static int getIntValue(Node n) {
53         return ((Number JavaDoc)n.getLiteral().getValue()).intValue();
54     }
55    
56     /**
57      * Compare two numeric nodes.
58      * @param n1 the first numeric valued literal node
59      * @param n2 the second numeric valued literal node
60      * @return -1 if n1 is less than n2, 0 if n1 equals n2 and +1 if n1 greater than n2
61      * @throws ClassCastException if either not is not numeric
62      */

63     public static int compareNumbers(Node n1, Node n2) {
64         if (n1.isLiteral() && n2.isLiteral()) {
65             Object JavaDoc v1 = n1.getLiteral().getValue();
66             Object JavaDoc v2 = n2.getLiteral().getValue();
67             if (v1 instanceof Number JavaDoc && v2 instanceof Number JavaDoc) {
68                 if (v1 instanceof Float JavaDoc || v1 instanceof Double JavaDoc
69                         || v1 instanceof Float JavaDoc || v2 instanceof Double JavaDoc) {
70                             double d1 = ((Number JavaDoc)v1).doubleValue();
71                             double d2 = ((Number JavaDoc)v2).doubleValue();
72                             return (d1 < d2) ? -1 : ( (d1 == d2) ? 0 : +1 );
73                 } else {
74                     long l1 = ((Number JavaDoc)v1).longValue();
75                     long l2 = ((Number JavaDoc)v2).longValue();
76                     return (l1 < l2) ? -1 : ( (l1 == l2) ? 0 : +1 );
77                 }
78             }
79         }
80         throw new ClassCastException JavaDoc("Non-numeric literal in compareNumbers");
81     }
82     
83     /**
84      * Check whether a Node is an Instant (DateTime) value
85      */

86     public static boolean isInstant(Node n) {
87         if (n.isLiteral()) {
88             Object JavaDoc o = n.getLiteral().getValue();
89             return (o instanceof XSDDateTime);
90         } else {
91             return false;
92         }
93     }
94     
95     /**
96      * Compare two time Instant nodes.
97      * @param n1 the first time instant (XSDDateTime) valued literal node
98      * @param n2 the second time instant (XSDDateTime) valued literal node
99      * @return -1 if n1 is less than n2, 0 if n1 equals n2 and +1 if n1 greater than n2
100      * @throws ClassCastException if either not is not numeric
101      */

102     public static int compareInstants(Node n1, Node n2) {
103         if (n1.isLiteral() && n2.isLiteral()) {
104             Object JavaDoc v1 = n1.getLiteral().getValue();
105             Object JavaDoc v2 = n2.getLiteral().getValue();
106             if (v1 instanceof XSDDateTime && v2 instanceof XSDDateTime) {
107                 XSDDateTime a = (XSDDateTime) v1;
108                 XSDDateTime b = (XSDDateTime) v2;
109                 return a.compare(b);
110             }
111         }
112         throw new ClassCastException JavaDoc("Non-numeric literal in compareNumbers");
113     }
114
115     /**
116      * Helper - returns the (singleton) value for the given property on the given
117      * root node in the data graph.
118      */

119     public static Node getPropValue(Node root, Node prop, Finder context) {
120         return doGetPropValue(context.find(new TriplePattern(root, prop, null)));
121     }
122    
123     /**
124      * Helper - returns the (singleton) value for the given property on the given
125      * root node in the data graph.
126      */

127     public static Node getPropValue(Node root, Node prop, Graph context) {
128         return doGetPropValue(context.find(root, prop, null));
129     }
130     
131     /**
132      * Helper - returns the (singleton) value for the given property on the given
133      * root node in the data graph.
134      */

135     public static Node getPropValue(Node root, Node prop, RuleContext context) {
136         return doGetPropValue(context.find(root, prop, null));
137     }
138     
139     /**
140      * Internall implementation of all the getPropValue variants.
141      */

142     private static Node doGetPropValue(ClosableIterator it) {
143         Node result = null;
144         if (it.hasNext()) {
145             result = ((Triple)it.next()).getObject();
146         }
147         it.close();
148         return result;
149     }
150     
151     /**
152      * Convert an (assumed well formed) RDF list to a java list of Nodes
153      * @param root the root node of the list
154      * @param context the graph containing the list assertions
155      */

156     public static List convertList(Node root, RuleContext context) {
157         return convertList(root, context, new LinkedList());
158     }
159     
160     /**
161      * Convert an (assumed well formed) RDF list to a java list of Nodes
162      */

163     private static List convertList(Node node, RuleContext context, List sofar) {
164         if (node == null || node.equals(RDF.nil.asNode())) return sofar;
165         Node next = getPropValue(node, RDF.first.asNode(), context);
166         if (next != null) {
167             sofar.add(next);
168             return convertList(getPropValue(node, RDF.rest.asNode(), context), context, sofar);
169         } else {
170             return sofar;
171         }
172     }
173     
174     /**
175      * Construct a new integer valued node
176      */

177     public static Node makeIntNode(int value) {
178         return Node.createLiteral(new LiteralLabel(new Integer JavaDoc(value)));
179     }
180     
181     /**
182      * Construct a new long valued node
183      */

184     public static Node makeLongNode(long value) {
185         if (value > Integer.MAX_VALUE) {
186             return Node.createLiteral(new LiteralLabel(new Long JavaDoc(value)));
187         } else {
188             return Node.createLiteral(new LiteralLabel(new Integer JavaDoc((int)value)));
189         }
190     }
191     
192     /**
193      * Construct a new double valued node
194      */

195     public static Node makeDoubleNode(double value) {
196         return Node.createLiteral(new LiteralLabel(new Double JavaDoc(value)));
197     }
198     
199     /**
200      * Construct an RDF list from the given array of nodes and assert it
201      * in the graph returning the head of the list.
202      */

203     public static Node makeList(Node[] nodes, Graph graph) {
204         return doMakeList(nodes, 0, graph);
205     }
206     
207     /**
208      * Internals of makeList.
209      */

210     private static Node doMakeList(Node[] nodes, int next, Graph graph) {
211         if (next < nodes.length) {
212             Node listNode = Node.createAnon();
213             graph.add(new Triple(listNode, RDF.Nodes.first, nodes[next]));
214             graph.add(new Triple(listNode, RDF.Nodes.rest, doMakeList(nodes, next+1, graph)));
215             return listNode;
216         } else {
217             return RDF.Nodes.nil;
218         }
219     }
220     
221     /**
222      * Open a resource file and read it all into a single string.
223      * Treats lines starting with # as comment lines, as per stringFromReader.
224      * @deprecated Use loadRuleParserFromResourceFile
225      */

226     public static String JavaDoc loadResourceFile( String JavaDoc filename ) {
227         return Rule.rulesStringFromReader( FileUtils.openResourceFile( filename ) );
228     }
229     
230     /**
231      * Open a resource file and read it all into a single string.
232      * Treats lines starting with # as comment lines, as per stringFromReader
233      */

234     public static Rule.Parser loadRuleParserFromResourceFile( String JavaDoc filename ) {
235         return Rule.rulesParserFromReader( FileUtils.openResourceFile( filename ) );
236     }
237     
238     /**
239      * Open a file defined by a URL and read all of it into a single string.
240      * If the URL fails it will try a plain file name as well.
241      */

242     public static String JavaDoc loadURLFile(String JavaDoc urlStr) throws IOException {
243         BufferedReader dataReader = FileUtils.readerFromURL( urlStr );
244         StringWriter sw = new StringWriter(1024);
245         char buff[] = new char[1024];
246         while (dataReader.ready()) {
247             int l = dataReader.read(buff);
248             if (l <= 0)
249                 break;
250             sw.write(buff, 0, l);
251         }
252         dataReader.close();
253         sw.close();
254         return sw.toString();
255     }
256     
257     /**
258      * Helper method - extracts the truth of a boolean configuration
259      * predicate.
260      * @param predicate the predicate to be tested
261      * @param configuration the configuration node
262      * @return null if there is no setting otherwise a Boolean giving the setting value
263      */

264     public static Boolean JavaDoc checkBinaryPredicate(Property predicate, Resource configuration) {
265         StmtIterator i = configuration.listProperties(predicate);
266         if (i.hasNext()) {
267             return new Boolean JavaDoc(i.nextStatement().getObject().toString().equalsIgnoreCase("true"));
268         } else {
269             return null;
270         }
271     }
272     
273     /**
274      * Helper method - extracts the value of an integer configuration
275      * predicate.
276      * @param predicate the predicate to be tested
277      * @param configuration the configuration node
278      * @return null if there is no such configuration parameter otherwise the value as an integer
279      */

280     public static Integer JavaDoc getIntegerPredicate(Property predicate, Resource configuration) {
281         StmtIterator i = configuration.listProperties(predicate);
282         if (i.hasNext()) {
283             RDFNode lit = i.nextStatement().getObject();
284             if (lit instanceof Literal) {
285                 return new Integer JavaDoc(((Literal)lit).getInt());
286             }
287         }
288         return null;
289     }
290
291     /**
292      * Convert the value of a boolean configuration parameter to a boolean value.
293      * Allows the value to be specified using a String or Boolean.
294      * @param parameter the configuration property being set (to help with error messages)
295      * @param value the parameter value
296      * @return the converted value
297      * @throws IllegalParameterException if the value can't be converted
298      */

299     public static boolean convertBooleanPredicateArg(Property parameter, Object JavaDoc value) {
300         if (value instanceof Boolean JavaDoc) {
301             return ((Boolean JavaDoc)value).booleanValue();
302         } else if (value instanceof String JavaDoc) {
303             return ((String JavaDoc)value).equalsIgnoreCase("true");
304         } else {
305             throw new IllegalParameterException("Illegal type for " + parameter + " setting - use a Boolean");
306         }
307         
308     }
309
310     /**
311      * Convert the value of an integer configuration parameter to an int value.
312      * Allows the value to be specified using a String or Number.
313      * @param parameter the configuration property being set (to help with error messages)
314      * @param value the parameter value
315      * @return the converted value
316      * @throws IllegalParameterException if the value can't be converted
317      */

318     public static int convertIntegerPredicateArg(Property parameter, Object JavaDoc value) {
319         if (value instanceof Number JavaDoc) {
320             return ((Number JavaDoc)value).intValue();
321         } else if (value instanceof String JavaDoc) {
322             try {
323                 return Integer.parseInt((String JavaDoc)value);
324             } catch (NumberFormatException JavaDoc e) {
325                 throw new IllegalParameterException("Illegal type for " + parameter + " setting - use an integer");
326             }
327         } else {
328             throw new IllegalParameterException("Illegal type for " + parameter + " setting - use an integer");
329         }
330     }
331     
332     /**
333      * Replace the value for a given parameter on the resource by a new value.
334      * @param config the resource whose values are to be updated
335      * @param parameter a predicate defining the parameter to be set
336      * @param value the new value
337      */

338     public static void updateParameter(Resource config, Property parameter, Object JavaDoc value) {
339         for (StmtIterator i = config.listProperties(parameter); i.hasNext(); ) {
340              i.next();
341              i.remove();
342         }
343         config.addProperty(parameter, value);
344     }
345 }
346
347 /*
348  * (c) Copyright 2003, 2004, 2005 Hewlett-Packard Development Company, LP
349  * All rights reserved.
350  *
351  * Redistribution and use in source and binary forms, with or without
352  * modification, are permitted provided that the following conditions
353  * are met:
354  * 1. Redistributions of source code must retain the above copyright
355  * notice, this list of conditions and the following disclaimer.
356  * 2. Redistributions in binary form must reproduce the above copyright
357  * notice, this list of conditions and the following disclaimer in the
358  * documentation and/or other materials provided with the distribution.
359  * 3. The name of the author may not be used to endorse or promote products
360  * derived from this software without specific prior written permission.
361  *
362  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
363  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
364  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
365  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
366  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
367  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
368  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
369  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
370  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
371  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
372  */

373
374
Popular Tags