source: gli/branches/rtl-gli/src/org/greenstone/gatherer/cdm/CommandTokenizer.java@ 18368

Last change on this file since 18368 was 8240, checked in by mdewsnip, 20 years ago

Removed unnecessary imports of org.greenstone.gatherer.Gatherer.

  • Property svn:keywords set to Author Date Id Revision
File size: 10.6 KB
Line 
1/**
2 *#########################################################################
3 *
4 * A component of the Gatherer application, part of the Greenstone digital
5 * library suite from the New Zealand Digital Library Project at the
6 * University of Waikato, New Zealand.
7 *
8 * <BR><BR>
9 *
10 * Author: John Thompson, Greenstone Digital Library, University of Waikato
11 *
12 * <BR><BR>
13 *
14 * Copyright (C) 1999 New Zealand Digital Library Project
15 *
16 * <BR><BR>
17 *
18 * This program is free software; you can redistribute it and/or modify
19 * it under the terms of the GNU General Public License as published by
20 * the Free Software Foundation; either version 2 of the License, or
21 * (at your option) any later version.
22 *
23 * <BR><BR>
24 *
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
29 *
30 * <BR><BR>
31 *
32 * You should have received a copy of the GNU General Public License
33 * along with this program; if not, write to the Free Software
34 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
35 *########################################################################
36 */
37package org.greenstone.gatherer.cdm;
38
39/**************************************************************************************
40 * Title: Gatherer
41 * Description: The Gatherer: a tool for gathering and enriching a digital collection.
42 * Company: The University of Waikato
43 * Written: 07/05/02
44 * Revised: 03/10/02 - Commented
45 **************************************************************************************/
46import java.io.BufferedReader;
47import java.util.StringTokenizer;
48import org.greenstone.gatherer.DebugStream;
49import org.greenstone.gatherer.util.StaticStrings;
50
51/** This class provides an extension to the standard StringTokenizer in that it recognizes quotes (or some form of bracketting) enclose a single token so in something like: <br>format Search '&lt;table&gt;&lt;img src=... &lt;/table&gt;'<br> the formatting string is parsed as a single token. Unfortunately this makes countTokens() unreliable for exact measurement of tokens remaining, and only useful for determining if there are tokens left to be processed (includes any that have already been read into command buffer).
52 * @author John Thompson, Greenstone Digital Library, University of Waikato
53 * @version 2.3
54 */
55public class CommandTokenizer {
56
57 static final public int BRACKET_ENCLOSED = 0;
58 static final public int DOUBLE_QUOTE_ENCLOSED = 1;
59 static final public int NORMAL = 2;
60 static final public int QUOTE_ENCLOSED = 3;
61
62 private BufferedReader in_stream;
63 private int count = -1;
64 private StringTokenizer internal_tokenizer;
65 private boolean strip_quotes = true;
66 /** Basic Constructor. Used to parse tokens from a string keeping tokens surrounded by speechmarks or square brackets intact. Thus something like:<br>
67 * collectionmeta collectionextra [l = en] "Hello World"<br>
68 * is tokenized thus<br>
69 * {'collectionmeta', 'collectionextra', 'l = en', 'Hello World'}
70 * @param command the command String you wish to tokenize
71 */
72 public CommandTokenizer(String command) {
73 this.internal_tokenizer = new StringTokenizer(command);
74 this.in_stream = null;
75 }
76
77 /** Advanced Constructor. As above but with one major difference. Since it is provided an input stream (presumably where the command string originated from), it is able to parse a quote enclosed command token that stretches over several lines. Each newline is preserved in the resulting token. There is an extra bitchslap here as comething like a collection extra might have html code in them that contain escaped speechmarks, so extra care must be taken not to break at them. Thus something like:<br>
78 * collectionmeta collectionextra [l = en] "<br>
79 * an example of the crazy as description we sometimes get which includes of all things something like <a href=\"this.html\"<br>
80 * >this</a> which you could easily see might be a problem if I parse this niavely."<br>
81 * is tokenized thus<br>
82 * {'collectionmeta', 'collectionextra', 'l = en', '\nan example of the crazy as description we sometimes get which includes of all things something like <a href=\"this.html\"\n>this</a> which you could easily see might be a problem if I parse this niavely.'}
83 * @param command the command String you wish to tokenize
84 * @param in_stream a BufferedReader from which the tokenizer can draw further lines as necessary
85 */
86 public CommandTokenizer(String command, BufferedReader in_stream) {
87 ///atherer.println("***** CommandTokenizer *****\nparse:\t" + command + "\n****************************");
88 this.internal_tokenizer = new StringTokenizer(command);
89 this.in_stream = in_stream;
90 }
91
92 public CommandTokenizer(String command, BufferedReader in_stream, boolean strip_quotes) {
93 this.internal_tokenizer = new StringTokenizer(command);
94 this.in_stream = in_stream;
95 this.strip_quotes = strip_quotes;
96 }
97
98 /** Returns the minumum number of remaining tokens before the tokenizer runs out of string. There may be more tokens than this count, but never less. The discrepancy is due to internal functionality and the fact we can't read ahead in the string or associated stream without risking the need for unpredictable push-back
99 * @return the minumum number of tokens available as an int
100 */
101 public int countTokens() {
102 if(count == 0 && internal_tokenizer.countTokens() > 1) {
103 return 1;
104 }
105 if(count == -1) {
106 count = internal_tokenizer.countTokens();
107 }
108 return count;
109 }
110
111 /** Determine if there are still tokens available.
112 * @return true if there are more tokens, false otherwise
113 */
114 public boolean hasMoreTokens() {
115 return internal_tokenizer.hasMoreTokens();
116 }
117
118 /** Method to retrieve the next token from the command, taking care to group tokens enclosed in speech marks.
119 * @return a String containing the next token from the command
120 */
121 public String nextToken() {
122 String result = null;
123 if(internal_tokenizer.hasMoreTokens()) {
124 StringBuffer buffer = new StringBuffer(internal_tokenizer.nextToken());
125 switch(buffer.charAt(0)) {
126 case StaticStrings.DOUBLEQUOTE_CHAR:
127 ///ystem.err.println("Building token wrapped by double quotes.");
128 result = buildToken(buffer, StaticStrings.DOUBLEQUOTE_CHAR, this.strip_quotes);
129 break;
130 case StaticStrings.SINGLEQUOTE_CHAR:
131 ///ystem.err.println("Building token wrapped by single quotes.");
132 result = buildToken(buffer, StaticStrings.SINGLEQUOTE_CHAR, this.strip_quotes);
133 break;
134 case StaticStrings.OPENBRACKET_CHAR:
135 ///ystem.err.println("Building token wrapped by brackets.");
136 result = buildToken(buffer, StaticStrings.CLOSEBRACKET_CHAR, false);
137 break;
138 default:
139 ///ystem.err.println("Returning plain string.");
140 result = buffer.toString();
141 }
142 buffer = null;
143 }
144 // Because of our tricky counting system we never want to have negative tokens remaining. In fact, unless the internal string buffer is empty, we will return a count of 1 anyway
145 if(count > 0) {
146 count = count - 1;
147 }
148 ///ystem.err.println("----- CommandTokenizer -----\ntoken:\t" + result + "\n----------------------------");
149 return result;
150 }
151
152 /** Parse in the next token. paying heed to enclosing characters demands, escaped characters, newlines and empty buffers and consequential unexpected end of tokens
153 * @param buffer the StringBuffer in which the partial token is stored (at the first bit that caused this method to be called)
154 * @param end_char the sentinel char we are watching for as it encloses a token
155 * @param strip_characters a boolean denoting whether the enclosing characters should be stripped off
156 * @return the token, either in its entirity less the enclosing characters if required or, if an unexpected end occured, whatever we parsed without its starting enclosing character, again only if required. In fact if we weren't asked to strip characters then we add the enclosing character back in
157 */
158 private String buildToken(StringBuffer buffer, char end_char, boolean strip_characters) {
159 while(buffer.length() == 1 || buffer.charAt(buffer.length() - 1) != end_char || (buffer.length() > 3 && buffer.charAt(buffer.length() - 2) == StaticStrings.BACKSLASH_CHAR)) {
160 try {
161 // The first version is for the basic tokenizer which has no idea of an input stream, so runs out tokens at the same time as the internal tokenizer does
162 if(internal_tokenizer.hasMoreTokens()) {
163 buffer.append(StaticStrings.SPACE_CHAR);
164 buffer.append(internal_tokenizer.nextToken());
165 }
166 // While the second version can draw more lines from the stream until eof occurs
167 else if(in_stream != null) {
168 String line_str = null;
169 while(!internal_tokenizer.hasMoreTokens() && (line_str = in_stream.readLine()) != null) {
170 ///atherer.println("+++++ CommandTokenizer +++++\nappend:\t" + line_str + "\n+++++++++++++++++++++++++++++");
171 // Its at this stage the our token count becomes completely putu
172 internal_tokenizer = new StringTokenizer(line_str);
173 buffer.append(StaticStrings.NEW_LINE_CHAR); // A new line in the final token
174 }
175 line_str = null;
176 if(internal_tokenizer.hasMoreTokens()) {
177 // Don't add a space if we just added a newline
178 if(buffer.charAt(buffer.length() - 1) != StaticStrings.NEW_LINE_CHAR) {
179 buffer.append(StaticStrings.SPACE_CHAR);
180 }
181 buffer.append(internal_tokenizer.nextToken());
182 }
183 // We've prematurely run out of content, so throw the dummy, or at least return whatever we managed to parse sans its opening character
184 else {
185 if(strip_characters) {
186 return buffer.substring(1);
187 }
188 else {
189 buffer.append(end_char);
190 return buffer.toString();
191 }
192 }
193 }
194 // We've prematurely run out of content, so throw the dummy, or at least return whatever we managed to parse sans its opening character
195 else {
196 if(strip_characters) {
197 return buffer.substring(1);
198 }
199 else {
200 buffer.append(end_char);
201 return buffer.toString();
202 }
203 }
204 }
205 // Exception thrown when we attempted reading from the input stream, so throw the dummy, or at least return whatever we managed to parse sans its opening character
206 catch(Exception exception) {
207 DebugStream.printStackTrace(exception);
208 if(strip_characters) {
209 return buffer.substring(1);
210 }
211 else {
212 buffer.append(end_char);
213 return buffer.toString();
214 }
215 }
216 }
217 // Return the string sans enclosing characters
218 if(buffer.length() >= 2 && strip_characters) {
219 return buffer.substring(1, buffer.length() - 1);
220 }
221 else {
222 return buffer.toString();
223 }
224 }
225}
Note: See TracBrowser for help on using the repository browser.