Temporarily add Ralph's changes to the source, which can generate
[cql-java-moved-to-github.git] / src / org / z3950 / zing / ralph / CQLTermNode.java
1 // $Id: CQLTermNode.java,v 1.1 2002-12-04 16:54:01 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 terminal node in a CQL parse-tree.
10  * A term node consists of the term String itself, together with,
11  * optionally, a qualifier string and a relation.  Neither or both of
12  * these must be provided - you can't have a qualifier without a
13  * relation or vice versa.
14  *
15  * @version     $Id: CQLTermNode.java,v 1.1 2002-12-04 16:54:01 mike Exp $
16  */
17 public class CQLTermNode extends CQLNode {
18     private String qualifier;
19     private CQLRelation relation;
20     private String term;
21
22     /**
23      * Creates a new term node with the specified <TT>qualifier</TT>,
24      * <TT>relation</TT> and <TT>term</TT>.  The first two may be
25      * <TT>null</TT>, but the <TT>term</TT> may not.
26      */
27     public CQLTermNode(String qualifier, CQLRelation relation, String term) {
28         this.qualifier = qualifier;
29         this.relation = relation;
30         this.term = term;
31     }
32
33     public String getQualifier() { return qualifier; }
34     public CQLRelation getRelation() { return relation; }
35     public String getTerm() { return term; }
36
37     public String toXCQL(int level, Vector prefixes) {
38         return (indent(level) + "<searchClause>\n" +
39                 renderPrefixes(level+1, prefixes) +
40                 indent(level+1) + "<index>" + xq(qualifier) + "</index>\n" +
41                 relation.toXCQL(level+1, new Vector()) +
42                 indent(level+1) + "<term>" + xq(term) + "</term>\n" +
43                 indent(level) + "</searchClause>\n");
44     }
45
46     public String toCQL() {
47         String quotedQualifier = maybeQuote(qualifier);
48         String quotedTerm = maybeQuote(term);
49         String res = quotedTerm;
50
51         if (!qualifier.equalsIgnoreCase("srw.serverChoice")) {
52             // ### We don't always need spaces around `relation'.
53             res = quotedQualifier + " " + relation.toCQL() + " " + quotedTerm;
54         }
55
56         return res;
57     }
58
59     
60     private Vector getAttrs(Properties config) throws PQFTranslationException {
61         Vector attrs = new Vector();
62
63         String attr;
64         attr = config.getProperty("qualifier." + qualifier);
65         if (attr == null)
66             throw new UnknownQualifierException(qualifier);
67         attrs.add(attr);
68
69         String rel = relation.getBase();
70         if (rel.equals("=")) {
71             rel = "eq";
72         } else if (rel.equals("<=")) {
73             rel = "le";
74         } else if (rel.equals(">=")) {
75             rel = "ge";
76         }
77         // ### Handling "any" and "all" properly would involve breaking
78         // the string down into a bunch of individual words and ORring
79         // or ANDing them together.  Another day.
80         attr = config.getProperty("relation." + rel);
81         if (attr == null)
82             throw new UnknownRelationException(rel);
83         attrs.add(attr);
84
85         String[] mods = relation.getModifiers();
86         for (int i = 0; i < mods.length; i++) {
87             attr = config.getProperty("relationModifier." + mods[i]);
88             if (attr == null)
89                 throw new UnknownRelationModifierException(mods[i]);
90             attrs.add(attr);
91         }
92
93         String pos = "unanchored";
94         String text = term;
95         if (text.length() > 0 && text.substring(0, 1).equals("^")) {
96             text = text.substring(1);
97             pos = "anchored";
98         }
99         attr = config.getProperty("position." + pos);
100         if (attr == null)
101             throw new UnknownPositionException(pos);
102         attrs.add(attr);
103
104         attr = config.getProperty("structure." + rel);
105         if (attr == null)
106             attr = config.getProperty("structure.*");
107         attrs.add(attr);
108
109         attr = config.getProperty("always");
110         if (attr != null)
111             attrs.add(attr);
112         return attrs;
113     }
114
115     public String toPQF(Properties config) throws PQFTranslationException {
116         Vector attrs=getAttrs(config);
117         
118         String attr, s = "";
119         for (int i = 0; i < attrs.size(); i++) {
120             attr = (String) attrs.get(i);
121             s += "@attr " + Utils.replaceString(attr, " ", " @attr ") + " ";
122         }
123
124         String text = term;
125         if (text.length() > 0 && text.substring(0, 1).equals("^"))
126             text = text.substring(1);
127         return s + maybeQuote(text);
128     }
129
130     static String maybeQuote(String str) {
131         // There _must_ be a better way to make this test ...
132         if (str.length() == 0 ||
133             str.indexOf('"') != -1 ||
134             str.indexOf(' ') != -1 ||
135             str.indexOf('\t') != -1 ||
136             str.indexOf('=') != -1 ||
137             str.indexOf('<') != -1 ||
138             str.indexOf('>') != -1 ||
139             str.indexOf('/') != -1 ||
140             str.indexOf('(') != -1 ||
141             str.indexOf(')') != -1) {
142             str = '"' + Utils.replaceString(str, "\"", "\\\"") + '"';
143         }
144
145         return str;
146     }
147     
148     /** Renders a parse-tree into a Yaz-style PQF string.
149      * PQF, or Prefix Query Format, is a cryptic but powerful notation
150      * that can be trivially mapped, one-to-one, int Z39.50 Type-1 and
151      * Type-101 queries.  A specification for the format can be found
152      * in
153      * <A href="http://indexdata.dk/yaz/doc/tools.php#PQF"
154      *  >Chapter 7 (Supporting Tools)</A> of the
155      * <A href="http://indexdata.dk/yaz/">YAZ</A> manual.
156      * <P>
157      * @param config
158      *  A <TT>Properties</TT> object containing configuration
159      *  information that specifies the mapping from CQL qualifiers,
160      *  relations, etc. to Type-1 attributes.  The mapping
161      *  specification is described in the cql-java distribution's
162      *  sample PQF-mapping configuration file,
163      *  <TT>etc/pqf.properties</TT>, which see.
164      * @return
165      *  A String containing a PQF query equivalent to the parse-tree
166      *  whose root is this node.  This may be fed into the tool of
167      *  your choice to obtain a BER-encoded packet.
168      */
169     public byte[] toType1(Properties config) throws PQFTranslationException {
170         String text = term;
171         if (text.length() > 0 && text.substring(0, 1).equals("^"))
172             text = text.substring(1);
173         String attr, attrList, term=maybeQuote(text);
174         System.out.println("in CQLTermNode.toType101(): PQF="+toPQF(config));
175         byte[] operand=new byte[text.length()+100];
176         int    i, j, offset, type, value;
177         offset=putTag(CONTEXT, 0, CONSTRUCTED, operand, 0); // op
178         operand[offset++]=(byte)(0x80&0xff); // indefinite length
179         offset=putTag(CONTEXT, 102, CONSTRUCTED, operand, offset); // AttributesPlusTerm
180         operand[offset++]=(byte)(0x80&0xff); // indefinite length
181         offset=putTag(CONTEXT, 44, CONSTRUCTED, operand, offset); // AttributeList
182         operand[offset++]=(byte)(0x80&0xff); // indefinite length
183         offset=putTag(UNIVERSAL, SEQUENCE, CONSTRUCTED, operand, offset);
184         operand[offset++]=(byte)(0x80&0xff);
185
186         Vector attrs=getAttrs(config);
187         for(i = 0; i < attrs.size(); i++) {
188             attrList = (String) attrs.get(i);
189             java.util.StringTokenizer st=new java.util.StringTokenizer(attrList);
190             while(st.hasMoreTokens()) {
191                 attr=st.nextToken();
192                 j=attr.indexOf('=');
193                 offset=putTag(CONTEXT, 120, PRIMITIVE, operand, offset);
194                 type=Integer.parseInt(attr.substring(0, j));
195                 offset=putLen(numLen(type), operand, offset);
196                 offset=putNum(type, operand, offset);
197                 
198                 offset=putTag(CONTEXT, 121, PRIMITIVE, operand, offset);
199                 value=Integer.parseInt(attr.substring(j+1));
200                 offset=putLen(numLen(value), operand, offset);
201                 offset=putNum(value, operand, offset);
202             }
203         }
204         operand[offset++]=0x00; // end of SEQUENCE
205         operand[offset++]=0x00;
206         operand[offset++]=0x00; // end of AttributeList
207         operand[offset++]=0x00;
208         
209         offset=putTag(CONTEXT, 45, PRIMITIVE, operand, offset); // general Term
210         byte[] t=term.getBytes();
211         offset=putLen(t.length, operand, offset);
212         System.arraycopy(t, 0, operand, offset, t.length);
213         offset+=t.length;
214         
215         operand[offset++]=0x00; // end of AttributesPlusTerm
216         operand[offset++]=0x00;
217         operand[offset++]=0x00; // end of Operand
218         operand[offset++]=0x00;
219         byte[] o=new byte[offset];
220         System.arraycopy(operand, 0, o, 0, offset);
221         return o;
222     }
223     
224 }