01: /*
02: * @(#)reader.java 1.2 04/12/06
03: *
04: * Copyright (c) 1997-2004 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package org.pnuts.io;
10:
11: import pnuts.lang.Context;
12: import pnuts.lang.PnutsFunction;
13: import pnuts.lang.PnutsException;
14: import pnuts.io.CharacterEncoding;
15: import org.pnuts.lib.PathHelper;
16: import java.io.InputStream;
17: import java.io.IOException;
18: import java.io.Reader;
19: import java.io.BufferedReader;
20: import java.io.InputStreamReader;
21: import java.io.FileInputStream;
22: import java.io.File;
23: import java.net.URL;
24: import java.net.URLConnection;
25:
26: /*
27: * function reader(input {, encoding })
28: */
29: public class reader extends PnutsFunction {
30:
31: public reader() {
32: super ("reader");
33: }
34:
35: public boolean defined(int nargs) {
36: return nargs == 1 || nargs == 2;
37: }
38:
39: private static Reader getReader(Object input, String encoding,
40: Context context) throws IOException {
41: if (input instanceof Reader) {
42: return (Reader) input;
43: } else if (input instanceof InputStream) {
44: return new BufferedReader(CharacterEncoding.getReader(
45: (InputStream) input, encoding, context));
46: } else if (input instanceof File) {
47: return new BufferedReader(CharacterEncoding.getReader(
48: new FileInputStream((File) input), encoding,
49: context));
50: } else if (input instanceof String) {
51: File file = PathHelper.getFile((String) input, context);
52: return new BufferedReader(CharacterEncoding.getReader(
53: new FileInputStream(file), encoding, context));
54: } else if (input instanceof URL) {
55: if (encoding == null) {
56: return URLHelper.getReader((URL) input, context);
57: } else {
58: return new BufferedReader(new InputStreamReader(
59: ((URL) input).openStream(), encoding));
60: }
61: } else {
62: throw new IllegalArgumentException(String.valueOf(input));
63: }
64: }
65:
66: protected Object exec(Object[] args, Context context) {
67: int nargs = args.length;
68: try {
69: if (nargs == 1) {
70: return getReader(args[0], null, context);
71: } else if (nargs == 2) {
72: return getReader(args[0], (String) args[1], context);
73: } else {
74: undefined(args, context);
75: return null;
76: }
77: } catch (IOException e) {
78: throw new PnutsException(e, context);
79: }
80: }
81:
82: public String toString() {
83: return "function reader((Reader|InputStream|URL|String|File) {, encoding } )";
84: }
85: }
|