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