3e42e1e101bf35163cf343b4eb721b2cc2999399
[cql-java-moved-to-github.git] / src / main / java / org / z3950 / zing / cql / CQLNode.java
1 // $Id: CQLNode.java,v 1.26 2007-07-03 13:36:03 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 node in a CQL parse-tree.
10  *
11  * @version     $Id: CQLNode.java,v 1.26 2007-07-03 13:36:03 mike Exp $
12  */
13 public abstract class CQLNode {
14     CQLNode() {}                // prevent javadoc from documenting this
15
16     /**
17      * Returns the name of the result-set to which this query is a
18      * reference, if and only if the entire query consists only of a
19      * result-set reference.  If it's anything else, including a
20      * boolean combination of a result-set reference with something
21      * else, then null is returned instead.
22      * @return the name of the referenced result-set
23      */
24     public String getResultSetName() {
25         return null;
26     }
27
28     /**
29      * Translates a parse-tree into an XCQL document.
30      * <P>
31      * @param level
32      *  The number of levels to indent the top element of the XCQL
33      *  document.  This will typically be 0 when invoked by an
34      *  application; it takes higher values when this method is
35      *  invoked recursively for nodes further down the tree.
36      * @return
37      *  A String containing an XCQL document equivalent to the
38      *  parse-tree whose root is this node.
39      */
40     public String toXCQL(int level) {
41         return toXCQL(level, null);
42     }
43
44     public String toXCQL(int level, Vector<CQLPrefix> prefixes) {
45         return toXCQL(level, prefixes, null);
46     }
47
48     abstract public String toXCQL(int level, Vector<CQLPrefix> prefixes,
49                                   Vector<ModifierSet> sortkeys);
50
51     protected static String renderPrefixes(int level, Vector prefixes) {
52         if (prefixes == null || prefixes.size() == 0)
53             return "";
54         String res = indent(level) + "<prefixes>\n";
55         for (int i = 0; i < prefixes.size(); i++) {
56             CQLPrefix p = (CQLPrefix) prefixes.get(i);
57             res += indent(level+1) + "<prefix>\n";
58             if (p.name != null)
59                 res += indent(level+2) + "<name>" + p.name + "</name>\n";
60             res += indent(level+2) +
61                 "<identifier>" + p.identifier + "</identifier>\n";
62             res += indent(level+1) + "</prefix>\n";
63         }
64         return res + indent(level) + "</prefixes>\n";
65     }
66
67     protected static String renderSortKeys(int level,
68                                            Vector<ModifierSet> sortkeys) {
69         if (sortkeys == null || sortkeys.size() == 0)
70             return "";
71         String res = indent(level) + "<sortKeys>\n";
72         for (int i = 0; i < sortkeys.size(); i++) {
73             ModifierSet key = sortkeys.get(i);
74             res += key.sortKeyToXCQL(level+1);
75         }
76         return res + indent(level) + "</sortKeys>\n";
77     }
78
79     /**
80      * Decompiles a parse-tree into a CQL query.
81      * <P>
82      * @return
83      *  A String containing a CQL query equivalent to the parse-tree
84      *  whose root is this node, so that compiling that query will
85      *  yield an identical tree.
86      */
87     abstract public String toCQL();
88
89     /**
90      * Renders a parse-tree into a Yaz-style PQF string.
91      * PQF, or Prefix Query Format, is a cryptic but powerful notation
92      * that can be trivially mapped, one-to-one, int Z39.50 Type-1 and
93      * Type-101 queries.  A specification for the format can be found
94      * in
95      * <A href="http://indexdata.dk/yaz/doc/tools.php#PQF"
96      *  >Chapter 7 (Supporting Tools)</A> of the
97      * <A href="http://indexdata.dk/yaz/">YAZ</A> manual.
98      * <P>
99      * @param config
100      *  A <TT>Properties</TT> object containing configuration
101      *  information that specifies the mapping from CQL indexes,
102      *  relations, etc. to Type-1 attributes.  The mapping
103      *  specification is described in the CQL-Java distribution's
104      *  sample PQF-mapping configuration file,
105      *  <TT>etc/pqf.properties</TT>, which see.
106      * @return
107      *  A String containing a PQF query equivalent to the parse-tree
108      *  whose root is this node.
109      */
110     abstract public String toPQF(Properties config)
111         throws PQFTranslationException;
112
113     /**
114      * Returns a String of spaces for indenting to the specified level.
115      */
116     protected static String indent(int level) { return Utils.indent(level); }
117
118     /**
119      * Returns the argument String quoted for XML.
120      * For example, each occurrence of <TT>&lt;</TT> is translated to
121      * <TT>&amp;lt;</TT>.
122      */
123     protected static String xq(String str) { return Utils.xq(str); }
124
125     /**
126      * Renders a parser-tree into a BER-endoded packet representing an
127      * equivalent Z39.50 Type-1 query.  If you don't know what that
128      * means, then you don't need this method :-)  This is useful
129      * primarily for SRW-to-Z39.50 gateways.
130      *
131      * @param config
132      *  A <TT>Properties</TT> object containing configuration
133      *  information that specifies the mapping from CQL indexes,
134      *  relations, etc. to Type-1 attributes.  The mapping
135      *  specification is described in the CQL-Java distribution's
136      *  sample PQF-mapping configuration file,
137      *  <TT>etc/pqf.properties</TT>, which see.
138      * @return
139      *  A byte array containing the BER packet.
140      * @see
141      *  <A href="ftp://ftp.rsasecurity.com/pub/pkcs/ascii/layman.asc"
142      *          >ftp://ftp.rsasecurity.com/pub/pkcs/ascii/layman.asc</A>
143      */
144     abstract public byte[] toType1BER(Properties config)
145         throws PQFTranslationException;
146
147     // ANS.1 classes
148     protected static final int UNIVERSAL   = 0;
149     protected static final int APPLICATION = 1;
150     protected static final int CONTEXT     = 2;
151     protected static final int PRIVATE     = 3;
152
153     // ASN.1 tag forms
154     protected static final int PRIMITIVE   = 0;
155     protected static final int CONSTRUCTED = 1;
156
157     // ASN.1 UNIVERSAL data types
158     public static final byte BOOLEAN          =  1;
159     public static final byte INTEGER          =  2;
160     public static final byte BITSTRING        =  3;
161     public static final byte OCTETSTRING      =  4;
162     public static final byte NULL             =  5;
163     public static final byte OBJECTIDENTIFIER =  6;
164     public static final byte OBJECTDESCRIPTOR =  7;
165     public static final byte EXTERNAL         =  8;
166     public static final byte ENUMERATED       = 10;
167     public static final byte SEQUENCE         = 16;
168     public static final byte SET              = 17;
169     public static final byte VISIBLESTRING    = 26;
170     public static final byte GENERALSTRING    = 27;
171
172     protected static final int putTag(int asn1class, int fldid, int form,
173                                       byte[] record, int offset) {
174         if (fldid < 31)
175             record[offset++] = (byte)(fldid + asn1class*64 + form*32);
176         else {
177             record[offset++] = (byte)(31 + asn1class*64 + form*32);
178             if (fldid < 128)
179                 record[offset++] = (byte)(fldid);
180             else {
181                 record[offset++] = (byte)(128 + fldid/128);
182                 record[offset++] = (byte)(fldid % 128);
183             }
184         }
185         return offset;
186     }
187
188     /**
189      * Put a length directly into a BER record.
190      *
191      * @param len length to put into record
192      * @return the new, incremented value of the offset parameter.
193      */
194     public // ### shouldn't this be protected?
195         static final int putLen(int len, byte[] record, int offset) {
196
197         if (len < 128)
198             record[offset++] = (byte)len;
199         else {
200             int t;
201             record[offset] = (byte)(lenLen(len) - 1);
202             for (t = record[offset]; t > 0; t--) {
203                 record[offset+t] = (byte)(len & 0xff);
204                 len >>= 8;
205             }
206             t = offset;
207             offset += (record[offset]&0xff) + 1;
208             record[t] += 128; // turn on bit 8 in length byte.
209         }
210         return offset;
211     }
212
213     /**
214      * Get the length needed to represent the given length.
215      *
216      * @param length determine length needed to encode this
217      * @return length needed to encode given length
218      */
219     protected // ### shouldn't this be private?
220         static final int lenLen(int length) {
221
222         return ((length < 128) ? 1 :
223             (length < 256) ? 2 :
224                 (length < 65536L) ? 3 : 4);
225     }
226
227     /**
228      * Get the length needed to represent the given number.
229      *
230      * @param num determine length needed to encode this
231      * @return length needed to encode given number
232      */
233     protected static final int numLen(long num) {
234         num = num < 0 ? -num : num;
235         // ### Wouldn't this be better done algorithmically?
236         // Or at least with the constants expressed in hex?
237         return ((num < 128) ? 1 :
238             (num < 32768) ? 2 :
239                 (num < 8388608) ? 3 :
240                     (num < 2147483648L) ? 4 :
241                         (num < 549755813888L) ? 5 :
242                             (num < 140737488355328L) ? 6 :
243                                 (num < 36028797018963968L) ? 7 : 8);
244     }
245
246     /**
247      * Put a number into a given buffer
248      *
249      * @param num number to put into buffer
250      * @param record buffer to use
251      * @param offset offset into buffer
252      * @return the new, incremented value of the offset parameter.
253      */
254     protected static final int putNum(long num, byte record[], int offset) {
255         int cnt=numLen(num);
256
257         for (int count = cnt - 1; count >= 0; count--) {
258             record[offset+count] = (byte)(num & 0xff);
259             num >>= 8;
260         }
261         return offset+cnt;
262     }
263
264     // Used only by the makeOID() method
265     private static final java.util.Hashtable<String, byte[]> madeOIDs =
266         new java.util.Hashtable<String, byte[]>(10);
267
268     protected static final byte[] makeOID(String oid) {
269         byte[] o;
270         int dot, offset = 0, oidOffset = 0, value;
271
272         if ((o = (byte[])madeOIDs.get(oid)) == null) {
273             o = new byte[100];
274
275             // Isn't this kind of thing excruciating in Java?
276             while (oidOffset < oid.length() &&
277               Character.isDigit(oid.charAt(oidOffset)) == true) {
278                 if (offset > 90) // too large
279                     return null;
280
281                 dot = oid.indexOf('.', oidOffset);
282                 if (dot == -1)
283                     dot = oid.length();
284
285                 value = Integer.parseInt(oid.substring(oidOffset, dot));
286
287                 if (offset == 0) {  // 1st two are special
288                     if (dot == -1) // ### can't happen: -1 is reassigned above
289                         return null; // can't be this short
290                     oidOffset = dot+1; // skip past '.'
291
292                     dot = oid.indexOf('.', oidOffset);
293                     if (dot == -1)
294                         dot = oid.length();
295
296                     // ### Eh?!
297                     value = value * 40 +
298                         Integer.parseInt(oid.substring(oidOffset,dot));
299                 }
300
301                 if (value < 0x80) {
302                     o[offset++] = (byte)value;
303                 } else {
304                     int count = 0;
305                     byte bits[] = new byte[12]; // save a 84 (12*7) bit number
306
307                     while (value != 0) {
308                         bits[count++] = (byte)(value & 0x7f);
309                         value >>= 7;
310                     }
311
312                     // Now place in the correct order
313                     while (--count > 0)
314                         o[offset++] = (byte)(bits[count] | 0x80);
315
316                     o[offset++] = bits[count];
317                 }
318
319                 dot = oid.indexOf('.', oidOffset);
320                 if (dot == -1)
321                     break;
322
323                 oidOffset = dot+1;
324             }
325
326             byte[] ptr = new byte[offset];
327             System.arraycopy(o, 0, ptr, 0, offset);
328             madeOIDs.put(oid, ptr);
329             return ptr;
330         }
331         return o;
332     }
333
334     public static final byte[] makeQuery(CQLNode root, Properties properties)
335         throws PQFTranslationException {
336         byte[] rpnStructure = root.toType1BER(properties);
337         byte[] qry = new byte[rpnStructure.length+100];
338         int offset = 0;
339         offset = putTag(CONTEXT, 1, CONSTRUCTED, qry, offset);
340         qry[offset++] = (byte)(0x80&0xff);  // indefinite length
341         offset = putTag(UNIVERSAL, OBJECTIDENTIFIER, PRIMITIVE, qry, offset);
342         byte[] oid = makeOID("1.2.840.10003.3.1"); // bib-1
343         offset = putLen(oid.length, qry, offset);
344         System.arraycopy(oid, 0, qry, offset, oid.length);
345         offset += oid.length;
346         System.arraycopy(rpnStructure, 0, qry, offset, rpnStructure.length);
347         offset += rpnStructure.length;
348         qry[offset++] = 0x00;  // end of query
349         qry[offset++] = 0x00;
350         byte[] q = new byte[offset];
351         System.arraycopy(qry, 0, q, 0, offset);
352         return q;
353     }
354 }