Add classes for visitor traversal
[cql-java-moved-to-github.git] / src / main / java / org / z3950 / zing / cql / CQLTermNode.java
1
2 package org.z3950.zing.cql;
3 import java.util.ArrayList;
4 import java.util.List;
5 import java.util.Properties;
6
7 /**
8  * Represents a terminal node in a CQL parse-tree.
9  * A term node consists of the term String itself, together with,
10  * optionally, an index string and a relation.  Neither or both of
11  * these must be provided - you can't have an index without a
12  * relation or vice versa.
13  *
14  */
15 public class CQLTermNode extends CQLNode {
16     private String index;
17     private CQLRelation relation;
18     private String term;
19
20     /**
21      * Creates a new term node with the specified <TT>index</TT>,
22      * <TT>relation</TT> and <TT>term</TT>.  The first two may be
23      * <TT>null</TT>, but the <TT>term</TT> may not.
24      */
25     public CQLTermNode(String index, CQLRelation relation, String term) {
26         this.index = index;
27         this.relation = relation;
28         this.term = term;
29     }
30
31     public String getIndex() { return index; }
32     public CQLRelation getRelation() { return relation; }
33     public String getTerm() { return term; }
34
35     private static boolean isResultSetIndex(String qual) {
36         return (qual.equals("srw.resultSet") ||
37                 qual.equals("srw.resultSetId") ||
38                 qual.equals("srw.resultSetName") ||
39                 qual.equals("cql.resultSet") ||
40                 qual.equals("cql.resultSetId") ||
41                 qual.equals("cql.resultSetName"));
42     }
43
44     @Override
45     public void traverse(CQLNodeVisitor visitor) {
46       //we visit relation first to allow filtering on relation type in the visitor
47       relation.traverse(visitor);
48       visitor.onTermNode(this);
49     }
50         
51     @Override
52     public String getResultSetName() {
53         if (isResultSetIndex(index))
54             return term;
55         else
56             return null;
57     }
58
59     @Override
60     void toXCQLInternal(XCQLBuilder b, int level, List<CQLPrefix> prefixes,
61                          List<ModifierSet> sortkeys) {
62       b.indent(level).append("<searchClause>\n");
63       renderPrefixes(b, level + 1, prefixes);
64       b.indent(level + 1).append("<index>").xq(index).append("</index>\n");
65       relation.toXCQLInternal(b, level + 1);
66       b.indent(level + 1).append("<term>").xq(term).append("</term>\n");
67       renderSortKeys(b, level + 1, sortkeys);
68       b.indent(level).append("</searchClause>\n");
69     }
70
71     @Override
72     public String toCQL() {
73         String quotedIndex = maybeQuote(index);
74         String quotedTerm = maybeQuote(term);
75         String res = quotedTerm;
76
77         if (index != null &&
78             !index.equalsIgnoreCase("srw.serverChoice") &&
79             !index.equalsIgnoreCase("cql.serverChoice")) {
80             // ### We don't always need spaces around `relation'.
81             res = quotedIndex + " " + relation.toCQL() + " " + quotedTerm;
82         }
83
84         return res;
85     }
86
87     // ### Interaction between this and its callers is not good as
88     //  regards truncation of the term and generation of truncation
89     //  attributes.  Change the interface to fix this.
90     private List<String> getAttrs(Properties config) throws PQFTranslationException {
91         List<String> attrs = new ArrayList<String>();
92
93         // Do this first so that if any other truncation or
94         // completeness attributes are generated, they "overwrite"
95         // those specified here.
96         //
97         //  ### This approach relies on an unpleasant detail of Index
98         //      Data's (admittedly definitive) implementation of PQF,
99         //      and should not relied upon.
100         //
101         String attr = config.getProperty("always");
102         if (attr != null)
103             attrs.add(attr);
104
105         attr = config.getProperty("index." + index);
106         if (attr == null)
107             attr = config.getProperty("qualifier." + index);
108         if (attr == null)
109             throw new UnknownIndexException(index);
110         attrs.add(attr);
111
112         String rel = relation.getBase();
113         if (rel.equals("=")) {
114             rel = "eq";
115         } else if (rel.equals("<=")) {
116             rel = "le";
117         } else if (rel.equals(">=")) {
118             rel = "ge";
119         }
120         // ### Handling "any" and "all" properly would involve breaking
121         // the string down into a bunch of individual words and ORring
122         // or ANDing them together.  Another day.
123         attr = config.getProperty("relation." + rel);
124         if (attr == null)
125             throw new UnknownRelationException(rel);
126         attrs.add(attr);
127
128         List<Modifier> mods = relation.getModifiers();
129         for (int i = 0; i < mods.size(); i++) {
130             String type = mods.get(i).type;
131             attr = config.getProperty("relationModifier." + type);
132             if (attr == null)
133                 throw new UnknownRelationModifierException(type);
134             attrs.add(attr);
135         }
136
137         String pos = "any";
138         String text = term;
139         if (text.length() > 0 && text.substring(0, 1).equals("^")) {
140             text = text.substring(1); // ### change not seen by caller
141             pos = "first";
142         }
143         int len = text.length();
144         if (len > 0 && text.substring(len-1, len).equals("^")) {
145             text = text.substring(0, len-1); // ### change not seen by caller
146             pos = pos.equals("first") ? "firstAndLast" : "last";
147             // ### in the firstAndLast case, the standard
148             //  pqf.properties file specifies that we generate a
149             //  completeness=whole-field attributem, which means that
150             //  we don't generate a position attribute at all.  Do we
151             //  care?  Does it matter?
152         }
153
154         attr = config.getProperty("position." + pos);
155         if (attr == null)
156             throw new UnknownPositionException(pos);
157         attrs.add(attr);
158
159         attr = config.getProperty("structure." + rel);
160         if (attr == null)
161             attr = config.getProperty("structure.*");
162         attrs.add(attr);
163
164         return attrs;
165     }
166
167     @Override
168     public String toPQF(Properties config) throws PQFTranslationException {
169         if (isResultSetIndex(index)) {
170             // Special case: ignore relation, modifiers, wildcards, etc.
171             // There's parallel code in toType1BER()
172             return "@set " + maybeQuote(term);
173         }
174
175         List<String> attrs = getAttrs(config);
176
177         String attr, s = "";
178         for (int i = 0; i < attrs.size(); i++) {
179             attr = (String) attrs.get(i);
180             s += "@attr " + attr.replace(" ", " @attr ") + " ";
181         }
182
183         String text = term;
184         if (text.length() > 0 && text.substring(0, 1).equals("^"))
185             text = text.substring(1);
186         int len = text.length();
187         if (len > 0 && text.substring(len-1, len).equals("^"))
188             text = text.substring(0, len-1);
189
190         return s + maybeQuote(text);
191     }
192
193     static String maybeQuote(String str) {
194        if (str == null)
195           return null;
196
197         // There _must_ be a better way to make this test ...
198         if (str.length() == 0 ||
199             str.indexOf('"') != -1 ||
200             str.indexOf(' ') != -1 ||
201             str.indexOf('\t') != -1 ||
202             str.indexOf('=') != -1 ||
203             str.indexOf('<') != -1 ||
204             str.indexOf('>') != -1 ||
205             str.indexOf('/') != -1 ||
206             str.indexOf('(') != -1 ||
207             str.indexOf(')') != -1) {
208             str = '"' + str.replace("\"", "\\\"") + '"';
209         }
210
211         return str;
212     }
213
214     @Override
215     public byte[] toType1BER(Properties config) throws PQFTranslationException {
216         if (isResultSetIndex(index)) {
217             // Special case: ignore relation, modifiers, wildcards, etc.
218             // There's parallel code in toPQF()
219             byte[] operand = new byte[term.length()+100];
220             int offset;
221             offset = putTag(CONTEXT, 0, CONSTRUCTED, operand, 0); // op
222             operand[offset++] = (byte)(0x80&0xff); // indefinite length
223             offset = putTag(CONTEXT, 31, PRIMITIVE, operand, offset); // ResultSetId
224             byte[] t = term.getBytes();
225             offset = putLen(t.length, operand, offset);
226             System.arraycopy(t, 0, operand, offset, t.length);
227             offset += t.length;
228             operand[offset++] = 0x00; // end of Operand
229             operand[offset++] = 0x00;
230             byte[] o = new byte[offset];
231             System.arraycopy(operand, 0, o, 0, offset);
232             return o;
233         }
234
235         String text = term;
236         if (text.length() > 0 && text.substring(0, 1).equals("^"))
237             text = text.substring(1);
238         int len = text.length();
239         if (len > 0 && text.substring(len-1, len).equals("^"))
240             text = text.substring(0, len-1);
241
242         String attr, attrList;
243         byte[] operand = new byte[text.length()+100];
244         int i, j, offset, type, value;
245         offset = putTag(CONTEXT, 0, CONSTRUCTED, operand, 0); // op
246         operand[offset++]=(byte)(0x80&0xff); // indefinite length
247         offset = putTag(CONTEXT, 102, CONSTRUCTED, operand, offset); // AttributesPlusTerm
248         operand[offset++] = (byte)(0x80&0xff); // indefinite length
249         offset = putTag(CONTEXT, 44, CONSTRUCTED, operand, offset); // AttributeList
250         operand[offset++] = (byte)(0x80&0xff); // indefinite length
251
252         List<String> attrs = getAttrs(config);
253         for(i = 0; i < attrs.size(); i++) {
254             attrList = (String) attrs.get(i);
255             java.util.StringTokenizer st =
256                 new java.util.StringTokenizer(attrList);
257             while (st.hasMoreTokens()) {
258                 attr = st.nextToken();
259                 j = attr.indexOf('=');
260                 offset = putTag(UNIVERSAL, SEQUENCE, CONSTRUCTED, operand, offset);
261                 operand[offset++] = (byte)(0x80&0xff);
262                 offset = putTag(CONTEXT, 120, PRIMITIVE, operand, offset);
263                 type = Integer.parseInt(attr.substring(0, j));
264                 offset = putLen(numLen(type), operand, offset);
265                 offset = putNum(type, operand, offset);
266
267                 offset = putTag(CONTEXT, 121, PRIMITIVE, operand, offset);
268                 value = Integer.parseInt(attr.substring(j+1));
269                 offset = putLen(numLen(value), operand, offset);
270                 offset = putNum(value, operand, offset);
271                 operand[offset++] = 0x00; // end of SEQUENCE
272                 operand[offset++] = 0x00;
273             }
274         }
275         operand[offset++] = 0x00; // end of AttributeList
276         operand[offset++] = 0x00;
277
278         offset = putTag(CONTEXT, 45, PRIMITIVE, operand, offset); // general Term
279         byte[] t = text.getBytes();
280         offset = putLen(t.length, operand, offset);
281         System.arraycopy(t, 0, operand, offset, t.length);
282         offset += t.length;
283
284         operand[offset++] = 0x00; // end of AttributesPlusTerm
285         operand[offset++] = 0x00;
286         operand[offset++] = 0x00; // end of Operand
287         operand[offset++] = 0x00;
288         byte[] o = new byte[offset];
289         System.arraycopy(operand, 0, o, 0, offset);
290         return o;
291     }
292 }