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