001: /*
002: * @(#)write.java 1.2 04/12/06
003: *
004: * Copyright (c) 2003,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 pnuts.lang.*;
012: import pnuts.lang.Runtime;
013: import java.io.*;
014:
015: public class write extends PnutsFunction {
016:
017: public write() {
018: super ("write");
019: }
020:
021: public boolean defined(int narg) {
022: return narg == 1 || narg == 3;
023: }
024:
025: public Object exec(Object[] args, Context context) {
026: PrintWriter writer = context.getWriter();
027: OutputStream output = context.getOutputStream();
028:
029: if (output == null && writer == null) {
030: return null;
031: }
032: int nargs = args.length;
033: if (nargs == 1) {
034: try {
035: Object arg0 = args[0];
036: if (arg0 instanceof Number) {
037: int ch = ((Number) arg0).intValue();
038: if (output != null) {
039: output.write(ch);
040: } else {
041: writer.write(ch);
042: }
043: } else if (arg0 instanceof Character) {
044: char ch = ((Character) arg0).charValue();
045: if (output != null) {
046: output.write(ch);
047: } else {
048: writer.write(ch);
049: }
050: } else if (arg0 instanceof byte[]) {
051: if (output != null) {
052: output.write((byte[]) arg0);
053: } else {
054: writer.write(new String((byte[]) arg0));
055: }
056: } else if (arg0 instanceof char[]) {
057: if (writer != null) {
058: char[] buf = (char[]) arg0;
059: writer.write(buf, 0, buf.length);
060: }
061: } else {
062: if (output != null) {
063: output.write((byte[]) Runtime.transform(
064: byte[].class, arg0));
065: } else {
066: char[] c = (char[]) Runtime.transform(
067: byte[].class, arg0);
068: writer.write(c, 0, c.length);
069: }
070: }
071: } catch (IOException ioe) {
072: throw new PnutsException(ioe, context);
073: }
074: } else if (nargs == 3) {
075: try {
076: Object arg0 = args[0];
077: int offset = ((Integer) args[1]).intValue();
078: int size = ((Integer) args[2]).intValue();
079: if (arg0 instanceof byte[]) {
080: if (output != null) {
081: byte[] buf = (byte[]) arg0;
082: output.write(buf, offset, size);
083: } else {
084: writer.write(new String((byte[]) arg0, offset,
085: size));
086: }
087: } else if (arg0 instanceof char[]) {
088: if (writer != null) {
089: writer.write((char[]) arg0, offset, size);
090: }
091: } else {
092: throw new IllegalArgumentException();
093: }
094: } catch (IOException ioe) {
095: throw new PnutsException(ioe, context);
096: }
097: } else {
098: undefined(args, context);
099: }
100: return null;
101: }
102:
103: public String toString() {
104: return "function write(c {, offset, size})";
105: }
106: }
|