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