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