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