01: /*
02: * @(#)writeDocument.java 1.2 04/12/06
03: *
04: * Copyright (c) 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.xml;
10:
11: import pnuts.lang.*;
12: import org.pnuts.lib.PathHelper;
13: import org.pnuts.util.*;
14: import javax.xml.parsers.*;
15: import javax.xml.transform.*;
16: import javax.xml.transform.stream.*;
17: import javax.xml.transform.dom.*;
18: import java.util.*;
19: import java.io.*;
20: import org.w3c.dom.Node;
21:
22: public class writeDocument extends PnutsFunction {
23:
24: public writeDocument() {
25: super ("writeDocument");
26: }
27:
28: public boolean defined(int nargs) {
29: return nargs >= 1 && nargs <= 3;
30: }
31:
32: protected Object exec(Object[] args, Context context) {
33: Map props = null;
34: Result result = new StreamResult(context.getWriter());
35: Source source;
36: Node node = null;
37: int nargs = args.length;
38: switch (nargs) {
39: case 3:
40: props = (Map) args[2];
41: case 2:
42: Object arg1 = args[1];
43: if (arg1 instanceof Result) {
44: result = (Result) arg1;
45: } else if (arg1 instanceof String) {
46: result = new StreamResult(PathHelper.getFile(
47: (String) arg1, context));
48: } else if (arg1 instanceof File) {
49: result = new StreamResult((File) arg1);
50: } else if (arg1 instanceof OutputStream) {
51: result = new StreamResult((OutputStream) arg1);
52: } else if (arg1 instanceof Writer) {
53: result = new StreamResult((Writer) arg1);
54: } else {
55: throw new IllegalArgumentException(String.valueOf(arg1));
56: }
57: case 1:
58: Object arg0 = args[0];
59: if (arg0 instanceof Source) {
60: source = (Source) arg0;
61: } else if (arg0 instanceof Node) {
62: node = (Node) arg0;
63: source = new DOMSource(node);
64: } else {
65: throw new IllegalArgumentException(String.valueOf(arg0));
66: }
67: break;
68: default:
69: undefined(args, context);
70: return null;
71: }
72: Transformer trans = Util.getTransformer(props, context);
73: try {
74: trans.transform(source, result);
75: } catch (TransformerException e) {
76: throw new PnutsException(e, context);
77: }
78: return null;
79: }
80:
81: public String toString() {
82: return "function writeDocument(doc {, out {, properties } } )";
83: }
84: }
|