01: /*
02: * @(#)applyTemplate.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.PnutsFunction;
13: import pnuts.lang.Runtime;
14: import pnuts.lang.Context;
15: import pnuts.lang.PnutsException;
16: import java.util.Map;
17: import java.io.Writer;
18: import java.io.IOException;
19:
20: /*
21: * applyTemplate(template, map)
22: */
23: public class applyTemplate extends PnutsFunction {
24:
25: public applyTemplate() {
26: super ("applyTemplate");
27: }
28:
29: public boolean defined(int nargs) {
30: return (nargs == 2);
31: }
32:
33: public static PnutsFunction getResult(final Template t,
34: final Map def) {
35: return new PnutsFunction() {
36: public boolean defined(int nargs) {
37: return nargs < 2;
38: }
39:
40: protected Object exec(Object[] args, Context context) {
41: int nargs = args.length;
42: Writer writer;
43: if (nargs == 0) {
44: writer = context.getWriter();
45: } else if (nargs == 1) {
46: writer = (Writer) args[0];
47: } else {
48: undefined(args, context);
49: return null;
50: }
51: try {
52: t.format(def, writer, context);
53: } catch (IOException e) {
54: throw new PnutsException(e, context);
55: }
56: return null;
57: }
58: };
59: }
60:
61: protected Object exec(Object args[], Context context) {
62: if (args.length == 2) {
63: return getResult((Template) args[0], (Map) args[1]);
64: } else {
65: undefined(args, context);
66: return null;
67: }
68: }
69:
70: public String toString() {
71: return "function applyTemplate(Template, Map)";
72: }
73: }
|