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