KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > socket > DelayedInput


1 /*
2  * Copyright 2000-2002,2004,2005 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package socket;
18
19 import java.io.FileInputStream JavaDoc;
20 import java.io.FilterInputStream JavaDoc;
21 import java.io.IOException JavaDoc;
22 import java.io.InputStream JavaDoc;
23 import java.io.PrintWriter JavaDoc;
24 import java.util.Random JavaDoc;
25
26 import org.xml.sax.Attributes JavaDoc;
27 import org.xml.sax.InputSource JavaDoc;
28 import org.xml.sax.Parser JavaDoc;
29 import org.xml.sax.SAXException JavaDoc;
30 import org.xml.sax.SAXParseException JavaDoc;
31 import org.xml.sax.XMLReader JavaDoc;
32 import org.xml.sax.helpers.DefaultHandler JavaDoc;
33 import org.xml.sax.helpers.ParserAdapter JavaDoc;
34 import org.xml.sax.helpers.ParserFactory JavaDoc;
35 import org.xml.sax.helpers.XMLReaderFactory JavaDoc;
36
37 /**
38  * This sample delays the input to the SAX parser to simulate reading data
39  * from a socket where data is not always immediately available. An XML
40  * parser should be able to parse the input and perform the necessary
41  * callbacks as data becomes available. So this is a good way to test
42  * any parser that implements the SAX2 <code>XMLReader</code> interface
43  * to see if it can parse data as it arrives.
44  * <p>
45  * <strong>Note:</strong> This sample uses NSGMLS-like output of elements
46  * and attributes interspersed with information about how many bytes are
47  * being read at a time.
48  *
49  * @author Andy Clark, IBM
50  *
51  * @version $Id: DelayedInput.java,v 1.8 2005/01/11 13:47:23 mrglavas Exp $
52  */

53 public class DelayedInput
54     extends DefaultHandler JavaDoc {
55
56     //
57
// Constants
58
//
59

60     // feature ids
61

62     /** Namespaces feature id (http://xml.org/sax/features/namespaces). */
63     protected static final String JavaDoc NAMESPACES_FEATURE_ID = "http://xml.org/sax/features/namespaces";
64
65     /** Validation feature id (http://xml.org/sax/features/validation). */
66     protected static final String JavaDoc VALIDATION_FEATURE_ID = "http://xml.org/sax/features/validation";
67
68     /** Schema validation feature id (http://apache.org/xml/features/validation/schema). */
69     protected static final String JavaDoc SCHEMA_VALIDATION_FEATURE_ID = "http://apache.org/xml/features/validation/schema";
70
71     /** Schema full checking feature id (http://apache.org/xml/features/validation/schema-full-checking). */
72     protected static final String JavaDoc SCHEMA_FULL_CHECKING_FEATURE_ID = "http://apache.org/xml/features/validation/schema-full-checking";
73
74     // default settings
75

76     /** Default parser name. */
77     protected static final String JavaDoc DEFAULT_PARSER_NAME = "org.apache.xerces.parsers.SAXParser";
78
79     /** Default namespaces support (true). */
80     protected static final boolean DEFAULT_NAMESPACES = true;
81
82     /** Default validation support (false). */
83     protected static final boolean DEFAULT_VALIDATION = false;
84
85     /** Default Schema validation support (false). */
86     protected static final boolean DEFAULT_SCHEMA_VALIDATION = false;
87
88     /** Default Schema full checking support (false). */
89     protected static final boolean DEFAULT_SCHEMA_FULL_CHECKING = false;
90
91     //
92
// Data
93
//
94

95     /** Print writer. */
96     protected PrintWriter JavaDoc fOut;
97
98     //
99
// Constructors
100
//
101

102     /** Default constructor. */
103     public DelayedInput() {
104     } // <init>()
105

106     //
107
// ContentHandler methods
108
//
109

110     /** Start element. */
111     public void startElement(String JavaDoc uri, String JavaDoc localpart, String JavaDoc rawname,
112                              Attributes JavaDoc attrs) throws SAXException JavaDoc {
113
114         System.out.println("("+rawname);
115         int length = attrs != null ? attrs.getLength() : 0;
116         for (int i = 0; i < length; i++) {
117             System.out.println("A"+attrs.getQName(i)+' '+attrs.getValue(i));
118         }
119
120     } // startElement(String,String,String,Attributes)
121

122     /** End element. */
123     public void endElement(String JavaDoc uri, String JavaDoc localpart, String JavaDoc rawname)
124         throws SAXException JavaDoc {
125         System.out.println(")"+rawname);
126     } // endElement(String,String,String)
127

128     //
129
// ErrorHandler methods
130
//
131

132     /** Warning. */
133     public void warning(SAXParseException JavaDoc ex) throws SAXException JavaDoc {
134         printError("Warning", ex);
135     } // warning(SAXParseException)
136

137     /** Error. */
138     public void error(SAXParseException JavaDoc ex) throws SAXException JavaDoc {
139         printError("Error", ex);
140     } // error(SAXParseException)
141

142     /** Fatal error. */
143     public void fatalError(SAXParseException JavaDoc ex) throws SAXException JavaDoc {
144         printError("Fatal Error", ex);
145         throw ex;
146     } // fatalError(SAXParseException)
147

148     //
149
// Protected methods
150
//
151

152     /** Prints the error message. */
153     protected void printError(String JavaDoc type, SAXParseException JavaDoc ex) {
154
155         System.err.print("[");
156         System.err.print(type);
157         System.err.print("] ");
158         String JavaDoc systemId = ex.getSystemId();
159         if (systemId != null) {
160             int index = systemId.lastIndexOf('/');
161             if (index != -1)
162                 systemId = systemId.substring(index + 1);
163             System.err.print(systemId);
164         }
165         System.err.print(':');
166         System.err.print(ex.getLineNumber());
167         System.err.print(':');
168         System.err.print(ex.getColumnNumber());
169         System.err.print(": ");
170         System.err.print(ex.getMessage());
171         System.err.println();
172         System.err.flush();
173
174     } // printError(String,SAXParseException)
175

176     //
177
// Classes
178
//
179

180     /**
181      * Delayed input stream filter. This class will limit block reads to a small
182      * number of bytes (suitable for display on a standard 80 column terminal)
183      * pausing in small increments, randomly. This lets you can verify that the
184      * parser can parse the input and make the appropriate callbacks as the
185      * data arrives.
186      *
187      * @author Andy Clark, IBM
188      */

189     static class DelayedInputStream
190         extends FilterInputStream JavaDoc {
191
192         //
193
// Data
194
//
195

196         /** Random number generator. */
197         private Random JavaDoc fRandom = new Random JavaDoc(System.currentTimeMillis());
198
199         //
200
// Constructors
201
//
202

203         /** Constructs a delayed input stream from the specified input stream. */
204         public DelayedInputStream(InputStream JavaDoc in) {
205             super(in);
206         } // <init>(InputStream)
207

208         //
209
// InputStream methods
210
//
211

212         /** Performs a delayed block read. */
213         public int read(byte[] buffer, int offset, int length) throws IOException JavaDoc {
214
215             // keep read small enough for display
216
if (length > 48) {
217                 length = 48;
218             }
219             int count = 0;
220
221             // read bytes and pause
222
long before = System.currentTimeMillis();
223             count = in.read(buffer, offset, length);
224             try {
225                 Thread.currentThread().sleep(Math.abs(fRandom.nextInt()) % 2000);
226             }
227             catch (InterruptedException JavaDoc e) {
228                 e.printStackTrace(System.err);
229             }
230             long after = System.currentTimeMillis();
231
232             // print output
233
System.out.print("read "+count+" bytes in "+(after-before)+" ms: ");
234             printBuffer(buffer, offset, count);
235             System.out.println();
236
237             // return number of characters read
238
return count;
239
240         } // read(byte[],int,int):int
241

242         //
243
// Private methods
244
//
245

246         /** Prints the specified buffer. */
247         private void printBuffer(byte[] buffer, int offset, int length) {
248
249             // is there anything to do?
250
if (length <= 0) {
251                 System.out.print("no data read");
252                 return;
253             }
254
255             // print buffer
256
System.out.print('[');
257             for (int i = 0; i < length; i++) {
258                 switch ((char)buffer[offset + i]) {
259                     case '\r': {
260                         System.out.print("\\r");
261                         break;
262                     }
263                     case '\n': {
264                         System.out.print("\\n");
265                         break;
266                     }
267                     default: {
268                         System.out.print((char)buffer[offset + i]);
269                     }
270                 }
271             }
272             System.out.print(']');
273
274         } // printBuffer(byte[],int,int)
275

276     } // class DelayedInputStream
277

278     //
279
// MAIN
280
//
281

282     /** Main program entry point. */
283     public static void main(String JavaDoc argv[]) {
284
285         // is there anything to do?
286
if (argv.length == 0) {
287             printUsage();
288             System.exit(1);
289         }
290
291         // variables
292
DefaultHandler JavaDoc handler = new DelayedInput();
293         PrintWriter JavaDoc out = new PrintWriter JavaDoc(System.out);
294         XMLReader JavaDoc parser = null;
295         boolean namespaces = DEFAULT_NAMESPACES;
296         boolean validation = DEFAULT_VALIDATION;
297         boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION;
298         boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
299
300         // process arguments
301
for (int i = 0; i < argv.length; i++) {
302             String JavaDoc arg = argv[i];
303             if (arg.startsWith("-")) {
304                 String JavaDoc option = arg.substring(1);
305                 if (option.equals("p")) {
306                     // get parser name
307
if (++i == argv.length) {
308                         System.err.println("error: Missing argument to -p option.");
309                     }
310                     String JavaDoc parserName = argv[i];
311
312                     // create parser
313
try {
314                         parser = XMLReaderFactory.createXMLReader(parserName);
315                     }
316                     catch (Exception JavaDoc e) {
317                         try {
318                             Parser JavaDoc sax1Parser = ParserFactory.makeParser(parserName);
319                             parser = new ParserAdapter JavaDoc(sax1Parser);
320                             System.err.println("warning: Features and properties not supported on SAX1 parsers.");
321                         }
322                         catch (Exception JavaDoc ex) {
323                             parser = null;
324                             System.err.println("error: Unable to instantiate parser ("+DEFAULT_PARSER_NAME+")");
325                         }
326                     }
327                     continue;
328                 }
329                 if (option.equalsIgnoreCase("n")) {
330                     namespaces = option.equals("n");
331                     continue;
332                 }
333                 if (option.equalsIgnoreCase("v")) {
334                     validation = option.equals("v");
335                     continue;
336                 }
337                 if (option.equalsIgnoreCase("s")) {
338                     schemaValidation = option.equals("s");
339                     continue;
340                 }
341                 if (option.equalsIgnoreCase("f")) {
342                     schemaFullChecking = option.equals("f");
343                     continue;
344                 }
345                 if (option.equals("h")) {
346                     printUsage();
347                     continue;
348                 }
349             }
350
351             // use default parser?
352
if (parser == null) {
353
354                 // create parser
355
try {
356                     parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME);
357                 }
358                 catch (Exception JavaDoc e) {
359                     System.err.println("error: Unable to instantiate parser ("+DEFAULT_PARSER_NAME+")");
360                     continue;
361                 }
362             }
363
364             // set parser features
365
try {
366                 parser.setFeature(NAMESPACES_FEATURE_ID, namespaces);
367             }
368             catch (SAXException JavaDoc e) {
369                 System.err.println("warning: Parser does not support feature ("+NAMESPACES_FEATURE_ID+")");
370             }
371             try {
372                 parser.setFeature(VALIDATION_FEATURE_ID, validation);
373             }
374             catch (SAXException JavaDoc e) {
375                 System.err.println("warning: Parser does not support feature ("+VALIDATION_FEATURE_ID+")");
376             }
377             try {
378                 parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation);
379             }
380             catch (SAXException JavaDoc e) {
381                 System.err.println("warning: Parser does not support feature ("+SCHEMA_VALIDATION_FEATURE_ID+")");
382             }
383             try {
384                 parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
385             }
386             catch (SAXException JavaDoc e) {
387                 System.err.println("warning: Parser does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
388             }
389
390             // parse file
391
parser.setContentHandler(handler);
392             parser.setErrorHandler(handler);
393             try {
394                 System.out.println("# filename: "+arg);
395                 InputStream JavaDoc stream = new DelayedInputStream(new FileInputStream JavaDoc(arg));
396                 InputSource JavaDoc source = new InputSource JavaDoc(stream);
397                 source.setSystemId(arg);
398                 parser.parse(source);
399             }
400             catch (SAXParseException JavaDoc e) {
401                 // ignore
402
}
403             catch (Exception JavaDoc e) {
404                 System.err.println("error: Parse error occurred - "+e.getMessage());
405                 if (e instanceof SAXException JavaDoc) {
406                     e = ((SAXException JavaDoc)e).getException();
407                 }
408                 e.printStackTrace(System.err);
409             }
410         }
411
412     } // main(String[])
413

414     //
415
// Private static methods
416
//
417

418     /** Prints the usage. */
419     private static void printUsage() {
420
421         System.err.println("usage: java socket.DelayedInput (options) filename ...");
422         System.err.println();
423
424         System.err.println("options:");
425         System.err.println(" -p name Select parser by name.");
426         System.err.println(" -n | -N Turn on/off namespace processing.");
427         System.err.println(" -v | -V Turn on/off validation.");
428         System.err.println(" -s | -S Turn on/off Schema validation support.");
429         System.err.println(" NOTE: Not supported by all parsers.");
430         System.err.println(" -f | -F Turn on/off Schema full checking.");
431         System.err.println(" NOTE: Requires use of -s and not supported by all parsers.");
432         System.err.println(" -h This help screen.");
433         System.err.println();
434
435         System.err.println("defaults:");
436         System.err.println(" Parser: "+DEFAULT_PARSER_NAME);
437         System.err.print(" Namespaces: ");
438         System.err.println(DEFAULT_NAMESPACES ? "on" : "off");
439         System.err.print(" Validation: ");
440         System.err.println(DEFAULT_VALIDATION ? "on" : "off");
441         System.err.print(" Schema: ");
442         System.err.println(DEFAULT_SCHEMA_VALIDATION ? "on" : "off");
443         System.err.print(" Schema full checking: ");
444         System.err.println(DEFAULT_SCHEMA_FULL_CHECKING ? "on" : "off");
445
446     } // printUsage()
447

448 } // class DelayedInput
449
Popular Tags