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