Handle relations, improve XML rendering (wow, was that hard.
[cql-java-moved-to-github.git] / src / org / z3950 / zing / cql / CQLNode.java
1 // $Id: CQLNode.java,v 1.6 2002-10-29 10:15:58 mike Exp $
2
3 package org.z3950.zing.cql;
4
5
6 /**
7  * Represents a node in a CQL parse-tree ...
8  * ###
9  *
10  * @version     $Id: CQLNode.java,v 1.6 2002-10-29 10:15:58 mike Exp $
11  */
12 public abstract class CQLNode {
13     abstract String toXCQL(int level);
14     abstract String toCQL();
15
16     protected String indent(int level) {
17         String x = "";
18         while (level-- > 0) {
19             x += "  ";
20         }
21         return x;
22     }
23
24     // XML Quote --
25     //  s/&/&/g;
26     //  s/</&lt;/g;
27     //  s/>/&gt;/g;
28     // This is hideously inefficient, but I just don't see a better
29     // way using the standard JAVA library.
30     //
31     protected String xq(String str) {
32         str = replace(str, "&", "&amp;");
33         str = replace(str, "<", "&lt;");
34         str = replace(str, ">", "&gt;");
35         return str;
36     }
37
38     String replace(String str, String from, String to) {
39         StringBuffer sb = new StringBuffer();
40         int ix;                 // index of next `from'
41         int offset = 0;         // index of previous `from' + length(from)
42
43         while ((ix = str.indexOf(from, offset)) != -1) {
44             sb.append(str.substring(offset, ix));
45             sb.append(to);
46             offset = ix + from.length();
47         }
48
49         // End of string: append last bit and we're done
50         sb.append(str.substring(offset));
51         return sb.toString();
52     }
53
54     // Test harness
55     public static void main (String[] args) {
56         CQLNode n1 = new CQLTermNode("dc.author", "=", "kernighan");
57         CQLNode n2 = new CQLTermNode("dc.title", "all", "elements style");
58         CQLNode root = new CQLAndNode(n1, n2);
59         System.out.println(root.toXCQL(0));
60     }
61 }