01: /*
02: * @(#)formatTemplate.java 1.2 04/12/06
03: *
04: * Copyright (c) 2001-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.text;
10:
11: import pnuts.text.Template;
12: import pnuts.lang.*;
13: import java.util.*;
14: import java.io.*;
15:
16: /*
17: * formatTemplate(template, map)
18: * formatTemplate(template, map, output)
19: */
20: public class formatTemplate extends PnutsFunction {
21: public formatTemplate() {
22: super ("formatTemplate");
23: }
24:
25: public boolean defined(int nargs) {
26: return (nargs == 2 || nargs == 3);
27: }
28:
29: protected Object exec(Object args[], Context context) {
30: int nargs = args.length;
31: if (nargs == 2) {
32: PnutsFunction f = applyTemplate.getResult(
33: (Template) args[0], (Map) args[1]);
34: Context c = (Context) context.clone();
35: StringWriter buf = new StringWriter();
36: c.setWriter(buf);
37: f.call(new Object[] {}, c);
38: return buf.toString();
39: } else if (nargs == 3) {
40: PnutsFunction f = applyTemplate.getResult(
41: (Template) args[0], (Map) args[1]);
42: Context c = (Context) context.clone();
43: Object a = args[2];
44: if (a instanceof OutputStream) {
45: c.setOutputStream((OutputStream) a);
46: } else if (a instanceof Writer) {
47: c.setWriter((Writer) a);
48: } else {
49: throw new IllegalArgumentException(String.valueOf(a));
50: }
51: f.call(new Object[] {}, c);
52: return null;
53: } else {
54: undefined(args, context);
55: return null;
56: }
57: }
58:
59: public String toString() {
60: return "function formatTemplate(template, map {, output } )";
61: }
62: }
|