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