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