Fix test-harnesses and generator to work with new relation structure.
[cql-java-moved-to-github.git] / src / org / z3950 / zing / cql / CQLNode.java
1 // $Id: CQLNode.java,v 1.8 2002-10-30 11:13:18 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.8 2002-10-30 11:13:18 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     // I can't _believe_ I have to write this by hand in 2002 ...
39     protected static String replace(String str, String from, String to) {
40         StringBuffer sb = new StringBuffer();
41         int ix;                 // index of next `from'
42         int offset = 0;         // index of previous `from' + length(from)
43
44         while ((ix = str.indexOf(from, offset)) != -1) {
45             sb.append(str.substring(offset, ix));
46             sb.append(to);
47             offset = ix + from.length();
48         }
49
50         // End of string: append last bit and we're done
51         sb.append(str.substring(offset));
52         return sb.toString();
53     }
54
55     // Test harness
56     public static void main (String[] args) {
57         CQLNode n1 = new CQLTermNode("dc.author",
58                                      new CQLRelation("="),
59                                      "kernighan");
60         CQLNode n2 = new CQLTermNode("dc.title",
61                                      new CQLRelation("all"),
62                                      "elements style");
63         CQLNode root = new CQLAndNode(n1, n2);
64         System.out.println(root.toXCQL(0));
65     }
66 }