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