Remove CVS expansions
[cql-java-moved-to-github.git] / src / main / java / org / z3950 / zing / cql / CQLTermNode.java
1
2 package org.z3950.zing.cql;
3 import java.util.ArrayList;
4 import java.util.List;
5 import java.util.Properties;
6
7 /**
8  * Represents a terminal node in a CQL parse-tree.
9  * A term node consists of the term String itself, together with,
10  * optionally, an index string and a relation.  Neither or both of
11  * these must be provided - you can't have an index without a
12  * relation or vice versa.
13  *
14  */
15 public class CQLTermNode extends CQLNode {
16     private String index;
17     private CQLRelation relation;
18     private String term;
19
20     /**
21      * Creates a new term node with the specified <TT>index</TT>,
22      * <TT>relation</TT> and <TT>term</TT>.  The first two may be
23      * <TT>null</TT>, but the <TT>term</TT> may not.
24      */
25     public CQLTermNode(String index, CQLRelation relation, String term) {
26         this.index = index;
27         this.relation = relation;
28         this.term = term;
29     }
30
31     public String getIndex() { return index; }
32     public CQLRelation getRelation() { return relation; }
33     public String getTerm() { return term; }
34
35     private static boolean isResultSetIndex(String qual) {
36         return (qual.equals("srw.resultSet") ||
37                 qual.equals("srw.resultSetId") ||
38                 qual.equals("srw.resultSetName") ||
39                 qual.equals("cql.resultSet") ||
40                 qual.equals("cql.resultSetId") ||
41                 qual.equals("cql.resultSetName"));
42     }
43
44     @Override
45     public String getResultSetName() {
46         if (isResultSetIndex(index))
47             return term;
48         else
49             return null;
50     }
51
52     @Override
53     void toXCQLInternal(XCQLBuilder b, int level, List<CQLPrefix> prefixes,
54                          List<ModifierSet> sortkeys) {
55       b.indent(level).append("<searchClause>\n");
56       renderPrefixes(b, level + 1, prefixes);
57       b.indent(level + 1).append("<index>").xq(index).append("</index>\n");
58       relation.toXCQLInternal(b, level + 1);
59       b.indent(level + 1).append("<term>").xq(term).append("</term>\n");
60       renderSortKeys(b, level + 1, sortkeys);
61       b.indent(level).append("</searchClause>\n");
62     }
63
64     @Override
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 List<String> getAttrs(Properties config) throws PQFTranslationException {
84         List<String> attrs = new ArrayList<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         List<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     @Override
161     public String toPQF(Properties config) throws PQFTranslationException {
162         if (isResultSetIndex(index)) {
163             // Special case: ignore relation, modifiers, wildcards, etc.
164             // There's parallel code in toType1BER()
165             return "@set " + maybeQuote(term);
166         }
167
168         List<String> attrs = getAttrs(config);
169
170         String attr, s = "";
171         for (int i = 0; i < attrs.size(); i++) {
172             attr = (String) attrs.get(i);
173             s += "@attr " + attr.replace(" ", " @attr ") + " ";
174         }
175
176         String text = term;
177         if (text.length() > 0 && text.substring(0, 1).equals("^"))
178             text = text.substring(1);
179         int len = text.length();
180         if (len > 0 && text.substring(len-1, len).equals("^"))
181             text = text.substring(0, len-1);
182
183         return s + maybeQuote(text);
184     }
185
186     static String maybeQuote(String str) {
187        if (str == null)
188           return null;
189
190         // There _must_ be a better way to make this test ...
191         if (str.length() == 0 ||
192             str.indexOf('"') != -1 ||
193             str.indexOf(' ') != -1 ||
194             str.indexOf('\t') != -1 ||
195             str.indexOf('=') != -1 ||
196             str.indexOf('<') != -1 ||
197             str.indexOf('>') != -1 ||
198             str.indexOf('/') != -1 ||
199             str.indexOf('(') != -1 ||
200             str.indexOf(')') != -1) {
201             str = '"' + str.replace("\"", "\\\"") + '"';
202         }
203
204         return str;
205     }
206
207     @Override
208     public byte[] toType1BER(Properties config) throws PQFTranslationException {
209         if (isResultSetIndex(index)) {
210             // Special case: ignore relation, modifiers, wildcards, etc.
211             // There's parallel code in toPQF()
212             byte[] operand = new byte[term.length()+100];
213             int offset;
214             offset = putTag(CONTEXT, 0, CONSTRUCTED, operand, 0); // op
215             operand[offset++] = (byte)(0x80&0xff); // indefinite length
216             offset = putTag(CONTEXT, 31, PRIMITIVE, operand, offset); // ResultSetId
217             byte[] t = term.getBytes();
218             offset = putLen(t.length, operand, offset);
219             System.arraycopy(t, 0, operand, offset, t.length);
220             offset += t.length;
221             operand[offset++] = 0x00; // end of Operand
222             operand[offset++] = 0x00;
223             byte[] o = new byte[offset];
224             System.arraycopy(operand, 0, o, 0, offset);
225             return o;
226         }
227
228         String text = term;
229         if (text.length() > 0 && text.substring(0, 1).equals("^"))
230             text = text.substring(1);
231         int len = text.length();
232         if (len > 0 && text.substring(len-1, len).equals("^"))
233             text = text.substring(0, len-1);
234
235         String attr, attrList;
236         byte[] operand = new byte[text.length()+100];
237         int i, j, offset, type, value;
238         offset = putTag(CONTEXT, 0, CONSTRUCTED, operand, 0); // op
239         operand[offset++]=(byte)(0x80&0xff); // indefinite length
240         offset = putTag(CONTEXT, 102, CONSTRUCTED, operand, offset); // AttributesPlusTerm
241         operand[offset++] = (byte)(0x80&0xff); // indefinite length
242         offset = putTag(CONTEXT, 44, CONSTRUCTED, operand, offset); // AttributeList
243         operand[offset++] = (byte)(0x80&0xff); // indefinite length
244
245         List<String> attrs = getAttrs(config);
246         for(i = 0; i < attrs.size(); i++) {
247             attrList = (String) attrs.get(i);
248             java.util.StringTokenizer st =
249                 new java.util.StringTokenizer(attrList);
250             while (st.hasMoreTokens()) {
251                 attr = st.nextToken();
252                 j = attr.indexOf('=');
253                 offset = putTag(UNIVERSAL, SEQUENCE, CONSTRUCTED, operand, offset);
254                 operand[offset++] = (byte)(0x80&0xff);
255                 offset = putTag(CONTEXT, 120, PRIMITIVE, operand, offset);
256                 type = Integer.parseInt(attr.substring(0, j));
257                 offset = putLen(numLen(type), operand, offset);
258                 offset = putNum(type, operand, offset);
259
260                 offset = putTag(CONTEXT, 121, PRIMITIVE, operand, offset);
261                 value = Integer.parseInt(attr.substring(j+1));
262                 offset = putLen(numLen(value), operand, offset);
263                 offset = putNum(value, operand, offset);
264                 operand[offset++] = 0x00; // end of SEQUENCE
265                 operand[offset++] = 0x00;
266             }
267         }
268         operand[offset++] = 0x00; // end of AttributeList
269         operand[offset++] = 0x00;
270
271         offset = putTag(CONTEXT, 45, PRIMITIVE, operand, offset); // general Term
272         byte[] t = text.getBytes();
273         offset = putLen(t.length, operand, offset);
274         System.arraycopy(t, 0, operand, offset, t.length);
275         offset += t.length;
276
277         operand[offset++] = 0x00; // end of AttributesPlusTerm
278         operand[offset++] = 0x00;
279         operand[offset++] = 0x00; // end of Operand
280         operand[offset++] = 0x00;
281         byte[] o = new byte[offset];
282         System.arraycopy(operand, 0, o, 0, offset);
283         return o;
284     }
285 }