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