Debian Codegraph @

rhino/examples/File.java

raw symbols SCIP
1 /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 import org.mozilla.javascript.*;
8 import org.mozilla.javascript.annotations.JSConstructor;
9 import org.mozilla.javascript.annotations.JSFunction;
10 import org.mozilla.javascript.annotations.JSGetter;
11
12 import java.io.*;
13 import java.util.List;
14 import java.util.ArrayList;
15
16 /**
17 * Define a simple JavaScript File object.
18 *
19 * This isn't intended to be any sort of definitive attempt at a
20 * standard File object for JavaScript, but instead is an example
21 * of a more involved definition of a host object.
22 *
23 * Example of use of the File object:
24 * <pre>
25 * js> defineClass("File")
26 * js> file = new File("myfile.txt");
27 * [object File]
28 * js> file.writeLine("one"); <i>only now is file actually opened</i>
29 * js> file.writeLine("two");
30 * js> file.writeLine("thr", "ee");
31 * js> file.close(); <i>must close file before we can reopen for reading</i>
32 * js> var a = file.readLines(); <i>creates and fills an array with the contents of the file</i>
33 * js> a;
34 * one,two,three
35 * js>
36 * </pre>
37 *
38 *
39 * File errors or end-of-file signaled by thrown Java exceptions will
40 * be wrapped as JavaScript exceptions when called from JavaScript,
41 * and may be caught within JavaScript.
42 *
43 * @author Norris Boyd
44 */
45 public class File extends ScriptableObject {
46
47 /**
48 *
49 */
50 private static final long serialVersionUID = 2549960399774237828L;
51 /**
52 * The zero-parameter constructor.
53 *
54 * When Context.defineClass is called with this class, it will
55 * construct File.prototype using this constructor.
56 */
57 public File() {
58 }
59
60 /**
61 * The Java method defining the JavaScript File constructor.
62 *
63 * If the constructor has one or more arguments, and the
64 * first argument is not undefined, the argument is converted
65 * to a string as used as the filename.<p>
66 *
67 * Otherwise System.in or System.out is assumed as appropriate
68 * to the use.
69 */
70 @JSConstructor
71 public static Scriptable jsConstructor(Context cx, Object[] args,
72 Function ctorObj,
73 boolean inNewExpr)
74 {
75 File result = new File();
76 if (args.length == 0 || args[0] == Context.getUndefinedValue()) {
77 result.name = "";
78 result.file = null;
79 } else {
80 result.name = Context.toString(args[0]);
81 result.file = new java.io.File(result.name);
82 }
83 return result;
84 }
85
86 /**
87 * Returns the name of this JavaScript class, "File".
88 */
89 @Override
90 public String getClassName() {
91 return "File";
92 }
93
94 /**
95 * Get the name of the file.
96 *
97 * Used to define the "name" property.
98 */
99 @JSGetter
100 public String getName() {
101 return name;
102 }
103
104 /**
105 * Read the remaining lines in the file and return them in an array.
106 *
107 * Implements a JavaScript function.<p>
108 *
109 * This is a good example of creating a new array and setting
110 * elements in that array.
111 *
112 * @exception IOException if an error occurred while accessing the file
113 * associated with this object
114 */
115 @JSFunction
116 public Object readLines()
117 throws IOException
118 {
119 List<String> list = new ArrayList<String>();
120 String s;
121 while ((s = readLine()) != null) {
122 list.add(s);
123 }
124 String[] lines = list.toArray(new String[list.size()]);
125 Scriptable scope = ScriptableObject.getTopLevelScope(this);
126 Context cx = Context.getCurrentContext();
127 return cx.newObject(scope, "Array", lines);
128 }
129
130 /**
131 * Read a line.
132 *
133 * Implements a JavaScript function.
134 * @exception IOException if an error occurred while accessing the file
135 * associated with this object, or EOFException if the object
136 * reached the end of the file
137 */
138 @JSFunction
139 public String readLine() throws IOException {
140 return getReader().readLine();
141 }
142
143 /**
144 * Read a character.
145 *
146 * @exception IOException if an error occurred while accessing the file
147 * associated with this object, or EOFException if the object
148 * reached the end of the file
149 */
150 @JSFunction
151 public String readChar() throws IOException {
152 int i = getReader().read();
153 if (i == -1)
154 return null;
155 char[] charArray = { (char) i };
156 return new String(charArray);
157 }
158
159 /**
160 * Write strings.
161 *
162 * Implements a JavaScript function. <p>
163 *
164 * This function takes a variable number of arguments, converts
165 * each argument to a string, and writes that string to the file.
166 * @exception IOException if an error occurred while accessing the file
167 * associated with this object
168 */
169 @JSFunction
170 public static void write(Context cx, Scriptable thisObj,
171 Object[] args, Function funObj)
172 throws IOException
173 {
174 write0(thisObj, args, false);
175 }
176
177 /**
178 * Write strings and a newline.
179 *
180 * Implements a JavaScript function.
181 * @exception IOException if an error occurred while accessing the file
182 * associated with this object
183 *
184 */
185 @JSFunction
186 public static void writeLine(Context cx, Scriptable thisObj,
187 Object[] args, Function funObj)
188 throws IOException
189 {
190 write0(thisObj, args, true);
191 }
192
193 @JSGetter
194 public int getLineNumber()
195 throws FileNotFoundException
196 {
197 return getReader().getLineNumber();
198 }
199
200 /**
201 * Close the file. It may be reopened.
202 *
203 * Implements a JavaScript function.
204 * @exception IOException if an error occurred while accessing the file
205 * associated with this object
206 */
207 @JSFunction
208 public void close() throws IOException {
209 if (reader != null) {
210 reader.close();
211 reader = null;
212 } else if (writer != null) {
213 writer.close();
214 writer = null;
215 }
216 }
217
218 /**
219 * Finalizer.
220 *
221 * Close the file when this object is collected.
222 */
223 @Override
224 protected void finalize() {
225 try {
226 close();
227 }
228 catch (IOException e) {
229 }
230 }
231
232 /**
233 * Get the Java reader.
234 */
235 @JSFunction("getReader")
236 public Object getJSReader() {
237 if (reader == null)
238 return null;
239 // Here we use toObject() to "wrap" the BufferedReader object
240 // in a Scriptable object so that it can be manipulated by
241 // JavaScript.
242 Scriptable parent = ScriptableObject.getTopLevelScope(this);
243 return Context.javaToJS(reader, parent);
244 }
245
246 /**
247 * Get the Java writer.
248 *
249 * @see File#getReader
250 *
251 */
252 @JSFunction
253 public Object getWriter() {
254 if (writer == null)
255 return null;
256 Scriptable parent = ScriptableObject.getTopLevelScope(this);
257 return Context.javaToJS(writer, parent);
258 }
259
260 /**
261 * Get the reader, checking that we're not already writing this file.
262 */
263 private LineNumberReader getReader() throws FileNotFoundException {
264 if (writer != null) {
265 throw Context.reportRuntimeError("already writing file \""
266 + name
267 + "\"");
268 }
269 if (reader == null)
270 reader = new LineNumberReader(file == null
271 ? new InputStreamReader(System.in)
272 : new FileReader(file));
273 return reader;
274 }
275
276 /**
277 * Perform the guts of write and writeLine.
278 *
279 * Since the two functions differ only in whether they write a
280 * newline character, move the code into a common subroutine.
281 *
282 */
283 private static void write0(Scriptable thisObj, Object[] args, boolean eol)
284 throws IOException
285 {
286 File thisFile = checkInstance(thisObj);
287 if (thisFile.reader != null) {
288 throw Context.reportRuntimeError("already writing file \""
289 + thisFile.name
290 + "\"");
291 }
292 if (thisFile.writer == null)
293 thisFile.writer = new BufferedWriter(
294 thisFile.file == null ? new OutputStreamWriter(System.out)
295 : new FileWriter(thisFile.file));
296 for (int i=0; i < args.length; i++) {
297 String s = Context.toString(args[i]);
298 thisFile.writer.write(s, 0, s.length());
299 }
300 if (eol)
301 thisFile.writer.newLine();
302 }
303
304 /**
305 * Perform the instanceof check and return the downcasted File object.
306 *
307 * This is necessary since methods may reside in the File.prototype
308 * object and scripts can dynamically alter prototype chains. For example:
309 * <pre>
310 * js> defineClass("File");
311 * js> o = {};
312 * [object Object]
313 * js> o.__proto__ = File.prototype;
314 * [object File]
315 * js> o.write("hi");
316 * js: called on incompatible object
317 * </pre>
318 * The runtime will take care of such checks when non-static Java methods
319 * are defined as JavaScript functions.
320 */
321 private static File checkInstance(Scriptable obj) {
322 if (obj == null || !(obj instanceof File)) {
323 throw Context.reportRuntimeError("called on incompatible object");
324 }
325 return (File) obj;
326 }
327
328 /**
329 * Some private data for this class.
330 */
331 private String name;
332 private java.io.File file; // may be null, meaning to use System.out or .in
333 private LineNumberReader reader;
334 private BufferedWriter writer;
335 }
336