001: /*
002: * @(#)parse.java 1.2 04/12/06
003: *
004: * Copyright (c) 1997-2004 Sun Microsystems, Inc. All Rights Reserved.
005: *
006: * See the file "LICENSE.txt" for information on usage and redistribution
007: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
008: */
009: package org.pnuts.lib;
010:
011: import java.io.InputStream;
012: import java.io.File;
013: import java.io.FileInputStream;
014: import java.io.Reader;
015: import java.io.IOException;
016: import java.net.URL;
017: import pnuts.lang.Context;
018: import pnuts.lang.Runtime;
019: import pnuts.lang.Pnuts;
020: import pnuts.lang.PnutsFunction;
021: import pnuts.lang.PnutsException;
022: import pnuts.lang.ParseException;
023:
024: public class parse extends PnutsFunction {
025:
026: public parse() {
027: super ("parse");
028: }
029:
030: public boolean defined(int nargs) {
031: return nargs == 1;
032: }
033:
034: static Pnuts parse(Object arg, Context context) {
035: if (arg instanceof Pnuts) {
036: return (Pnuts) arg;
037: } else {
038: try {
039: if (arg instanceof String) {
040: return Pnuts.parse((String) arg);
041: } else if (arg instanceof URL) {
042: Pnuts parsed;
043: InputStream in = null;
044: URL url = (URL) arg;
045: try {
046: in = url.openStream();
047: return Pnuts.parse(Runtime.getScriptReader(in,
048: context), url, context);
049: } catch (IOException ioe1) {
050: throw new PnutsException(ioe1, context);
051: } finally {
052: if (in != null) {
053: try {
054: in.close();
055: } catch (IOException ioe) {
056: }
057: }
058: }
059: } else if (arg instanceof File) {
060: Pnuts parsed;
061: File file = (File) arg;
062: InputStream in = null;
063: try {
064: in = new FileInputStream(file);
065: return Pnuts.parse(Runtime.getScriptReader(in,
066: context), file.toURL(), context);
067: } catch (IOException ioe1) {
068: throw new PnutsException(ioe1, context);
069: } finally {
070: if (in != null) {
071: try {
072: in.close();
073: } catch (IOException ioe) {
074: }
075: }
076: }
077: } else if (arg instanceof InputStream) {
078: return Pnuts.parse(Runtime.getScriptReader(
079: (InputStream) arg, context));
080: } else if (arg instanceof Reader) {
081: return Pnuts.parse((Reader) arg);
082: } else {
083: throw new IllegalArgumentException(String
084: .valueOf(arg));
085: }
086: } catch (IOException ioe) {
087: throw new PnutsException(ioe, context);
088: } catch (ParseException e) {
089: throw new PnutsException(e, context);
090: }
091: }
092: }
093:
094: protected Object exec(Object args[], Context context) {
095: if (args.length == 1) {
096: return parse(args[0], context);
097: } else {
098: undefined(args, context);
099: return null;
100: }
101: }
102:
103: public String toString() {
104: return "function parse(String|InputStream|Reader|File|URL)";
105: }
106: }
|