Hide some memebers as private, add getters
[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     static final int putLen(int len, byte[] record, int offset) {
195
196         if (len < 128)
197             record[offset++] = (byte)len;
198         else {
199             int t;
200             record[offset] = (byte)(lenLen(len) - 1);
201             for (t = record[offset]; t > 0; t--) {
202                 record[offset+t] = (byte)(len & 0xff);
203                 len >>= 8;
204             }
205             t = offset;
206             offset += (record[offset]&0xff) + 1;
207             record[t] += 128; // turn on bit 8 in length byte.
208         }
209         return offset;
210     }
211
212     /**
213      * Get the length needed to represent the given length.
214      *
215      * @param length determine length needed to encode this
216      * @return length needed to encode given length
217      */
218     protected // ### shouldn't this be private?
219         static final int lenLen(int length) {
220
221         return ((length < 128) ? 1 :
222             (length < 256) ? 2 :
223                 (length < 65536L) ? 3 : 4);
224     }
225
226     /**
227      * Get the length needed to represent the given number.
228      *
229      * @param num determine length needed to encode this
230      * @return length needed to encode given number
231      */
232     protected static final int numLen(long num) {
233         num = num < 0 ? -num : num;
234         // ### Wouldn't this be better done algorithmically?
235         // Or at least with the constants expressed in hex?
236         return ((num < 128) ? 1 :
237             (num < 32768) ? 2 :
238                 (num < 8388608) ? 3 :
239                     (num < 2147483648L) ? 4 :
240                         (num < 549755813888L) ? 5 :
241                             (num < 140737488355328L) ? 6 :
242                                 (num < 36028797018963968L) ? 7 : 8);
243     }
244
245     /**
246      * Put a number into a given buffer
247      *
248      * @param num number to put into buffer
249      * @param record buffer to use
250      * @param offset offset into buffer
251      * @return the new, incremented value of the offset parameter.
252      */
253     protected static final int putNum(long num, byte record[], int offset) {
254         int cnt=numLen(num);
255
256         for (int count = cnt - 1; count >= 0; count--) {
257             record[offset+count] = (byte)(num & 0xff);
258             num >>= 8;
259         }
260         return offset+cnt;
261     }
262
263     // Used only by the makeOID() method
264     private static final java.util.Hashtable<String, byte[]> madeOIDs =
265         new java.util.Hashtable<String, byte[]>(10);
266
267     protected static final byte[] makeOID(String oid) {
268         byte[] o;
269         int dot, offset = 0, oidOffset = 0, value;
270
271         if ((o = (byte[])madeOIDs.get(oid)) == null) {
272             o = new byte[100];
273
274             // Isn't this kind of thing excruciating in Java?
275             while (oidOffset < oid.length() &&
276               Character.isDigit(oid.charAt(oidOffset)) == true) {
277                 if (offset > 90) // too large
278                     return null;
279
280                 dot = oid.indexOf('.', oidOffset);
281                 if (dot == -1)
282                     dot = oid.length();
283
284                 value = Integer.parseInt(oid.substring(oidOffset, dot));
285
286                 if (offset == 0) {  // 1st two are special
287                     if (dot == -1) // ### can't happen: -1 is reassigned above
288                         return null; // can't be this short
289                     oidOffset = dot+1; // skip past '.'
290
291                     dot = oid.indexOf('.', oidOffset);
292                     if (dot == -1)
293                         dot = oid.length();
294
295                     // ### Eh?!
296                     value = value * 40 +
297                         Integer.parseInt(oid.substring(oidOffset,dot));
298                 }
299
300                 if (value < 0x80) {
301                     o[offset++] = (byte)value;
302                 } else {
303                     int count = 0;
304                     byte bits[] = new byte[12]; // save a 84 (12*7) bit number
305
306                     while (value != 0) {
307                         bits[count++] = (byte)(value & 0x7f);
308                         value >>= 7;
309                     }
310
311                     // Now place in the correct order
312                     while (--count > 0)
313                         o[offset++] = (byte)(bits[count] | 0x80);
314
315                     o[offset++] = bits[count];
316                 }
317
318                 dot = oid.indexOf('.', oidOffset);
319                 if (dot == -1)
320                     break;
321
322                 oidOffset = dot+1;
323             }
324
325             byte[] ptr = new byte[offset];
326             System.arraycopy(o, 0, ptr, 0, offset);
327             madeOIDs.put(oid, ptr);
328             return ptr;
329         }
330         return o;
331     }
332
333     public static final byte[] makeQuery(CQLNode root, Properties properties)
334         throws PQFTranslationException {
335         byte[] rpnStructure = root.toType1BER(properties);
336         byte[] qry = new byte[rpnStructure.length+100];
337         int offset = 0;
338         offset = putTag(CONTEXT, 1, CONSTRUCTED, qry, offset);
339         qry[offset++] = (byte)(0x80&0xff);  // indefinite length
340         offset = putTag(UNIVERSAL, OBJECTIDENTIFIER, PRIMITIVE, qry, offset);
341         byte[] oid = makeOID("1.2.840.10003.3.1"); // bib-1
342         offset = putLen(oid.length, qry, offset);
343         System.arraycopy(oid, 0, qry, offset, oid.length);
344         offset += oid.length;
345         System.arraycopy(rpnStructure, 0, qry, offset, rpnStructure.length);
346         offset += rpnStructure.length;
347         qry[offset++] = 0x00;  // end of query
348         qry[offset++] = 0x00;
349         byte[] q = new byte[offset];
350         System.arraycopy(qry, 0, q, 0, offset);
351         return q;
352     }
353 }