KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > barracuda > core > util > dom > CommaSeparatedDOMWriter


1 /*
2  * Copyright (C) 2003 Shawn Wilson [shawnw@atmreports.com]
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  *
18  * $Id: CommaSeparatedDOMWriter.java,v 1.1 2004/01/29 18:02:36 christianc Exp $
19  */

20 package org.enhydra.barracuda.core.util.dom;
21
22 // java imports:
23
import java.io.*;
24 import javax.servlet.http.*;
25
26
27 // 3rd-party imports:
28
import org.apache.log4j.*;
29 import org.enhydra.barracuda.core.util.dom.*;
30 import org.w3c.dom.*;
31 import org.w3c.dom.html.*;
32 import org.w3c.dom.CharacterData JavaDoc; // ambiguous with: java.lang.CharacterData
33

34 /**
35  * @author shawnw@atmreports.com
36  * @since saw_082603_2
37  */

38 public class CommaSeparatedDOMWriter implements DOMWriter {
39
40     //standard defs
41
private static final Class JavaDoc CLASS = CommaSeparatedDOMWriter.class;
42     private static final Logger logger = Logger.getLogger(CLASS);
43
44     //node definitions
45
public static final String JavaDoc DOCUMENT_TYPE = "table";
46     public static final String JavaDoc ELEMENT_ROW = "tr";
47     public static final String JavaDoc ELEMENT_HEADER = "th";
48     public static final String JavaDoc ELEMENT_COLUMN = "td";
49
50
51     //instance objects
52
protected String JavaDoc contentType = "text/plain";
53     protected String JavaDoc contentDisposition = null;
54     protected boolean preventCaching = false;
55     protected boolean leaveWriterOpen = false;
56     protected int maxAge = 0;
57
58     /**
59      * Create a new CommaSeparatedDOMWriter using the default values.
60      * The default content type is "text/plain".
61      * The default content disposition is to use none;
62      */

63     public CommaSeparatedDOMWriter() {
64         this(null, null);
65     }
66
67     /**
68      * Create a new CommaSeparatedDOMWriter with the supplied values.
69      *
70      * @param icontentType The content type to use
71      * @param icontentDisposition The content disposition to use
72      */

73     public CommaSeparatedDOMWriter(String JavaDoc icontentType, String JavaDoc icontentDisposition) {
74         setContentType(icontentType);
75         setContentDisposition(icontentDisposition);
76     }
77
78 //csc_012804_1_start
79
/**
80      * Set the content type (defaults to "text/html" or "text/xml" depending on the
81      * document type
82      */

83     public void setContentType(String JavaDoc icontentType) {
84         contentType = icontentType;
85     }
86
87     /**
88      * Get the content type
89      */

90     public String JavaDoc getContentType() {
91         return contentType;
92     }
93
94     /**
95      * Set the content disposition (ie. "inline; filename=foo.txt", defaults to null)
96      */

97     public void setContentDisposition(String JavaDoc icontentDisposition) {
98         contentDisposition = icontentDisposition;
99     }
100
101     /**
102      * Get the content disposition
103      */

104     public String JavaDoc getContentDisposition() {
105         return contentDisposition;
106     }
107
108     /**
109      * Set whether or not to leave the writer open after writing
110      */

111     public void setLeaveWriterOpen(boolean val) {
112         leaveWriterOpen = val;
113     }
114
115     /**
116      * Return true if the writer is configured to leave the output stream open
117      */

118     public boolean getLeaveWriterOpen() {
119         return leaveWriterOpen;
120     }
121
122
123     /**
124      * Prepare the response object
125      *
126      * @param node the DOM node to be written out
127      * @param resp the HttpServletResponse object
128      */

129     public void prepareResponse(HttpServletResponse resp) throws IOException {
130         //set the content type and disposition
131
if (logger.isDebugEnabled()) logger.debug("Setting content type:"+contentType+" content disposition:"+contentDisposition);
132         if (contentType!=null) resp.setContentType(contentType);
133         if (contentDisposition!=null) resp.setHeader("Content-Disposition", contentDisposition);
134
135         //if we need to prevent caching
136
if (preventCaching) {
137             //add the appropriate headers to the response
138
if (logger.isDebugEnabled()) logger.debug("updating resp hdr to prevent caching");
139             resp.setHeader("Pragma","no-cache");
140             resp.setHeader("Cache-Control","no-cache");
141             resp.setDateHeader("Expires", System.currentTimeMillis());
142
143         //csc_061202.1 - added
144
//otherwise explicitly give it a max-age (this will generally allow browsers like
145
//IE to page back in history without reloading, but if the user actually revisits the
146
//URL, then it will still be reloaded)
147
} else {
148             resp.setHeader("Cache-Control","max-age="+maxAge);
149             resp.setDateHeader("Last-Modified", System.currentTimeMillis());
150         }
151     }
152 //csc_012804_1_end
153

154     /**
155      * Write a DOM to a ServletResponse object.
156      * This method will automatically set the content type for you.
157      *
158      * @param node The DOM node to be written out
159      * @param resp The HttpServletResponse object to write to
160      */

161     public void write(Node node, HttpServletResponse resp) throws IOException {
162 //csc_012804_1_start
163
/*
164         if (contentType!=null) resp.setContentType(contentType);
165         if (contentDisposition!=null) resp.setHeader("Content-Disposition", contentDisposition);
166
167         //if we need to prevent caching
168         / *
169             //add the appropriate headers to the response
170             if (logger.isDebugEnabled()) logger.debug("updating resp hdr to prevent caching");
171             resp.setHeader("Pragma","no-cache");
172             resp.setHeader("Cache-Control","no-cache");
173             resp.setDateHeader("Expires", System.currentTimeMillis());
174          * /
175         resp.setHeader("Cache-Control", "max-age=0");
176         resp.setDateHeader("Last-Modified", System.currentTimeMillis());
177 */

178         if (getContentType()==null) setContentType((node instanceof HTMLDocument) ? "text/html" : "text/xml");
179         prepareResponse(resp);
180 //csc_012804_1_end
181

182         //write the dom
183
write(node, resp.getWriter());
184     }
185
186     /**
187      * Write a DOM to an OutputStream.
188      *
189      * @param node The DOM node to be written out
190      * @param out The OutputStream to be written to
191      */

192     public void write(Node node, OutputStream out) throws IOException {
193         write(node, new OutputStreamWriter(out));
194     }
195
196     /**
197      * Write a DOM to a Writer.
198      *
199      * @param node The DOM node to be written out
200      * @param writer The writer to be written to
201      */

202     public void write(Node node, Writer writer) throws IOException {
203         try { writeAll(node, writer); }
204         catch (DOMException e) {
205             logger.error("Error while writing node", e);
206         }
207         if (!leaveWriterOpen) writer.close();
208     }
209
210     protected void writeAll(Node node, Writer writer) throws IOException, DOMException {
211         if (node==null) {
212             return;
213         } else if (node instanceof Element) {
214             String JavaDoc name = node.getNodeName();
215             if (name.equals(ELEMENT_ROW)) {
216                 writeRow(node.getChildNodes(), writer);
217             } else if (name.equals(ELEMENT_HEADER)) {
218                 writeHeader(node.getChildNodes(), writer);
219             } else if (name.equals(ELEMENT_COLUMN)) {
220                 writeColumn(node.getChildNodes(), writer);
221             } else {
222                 writeAll(node.getChildNodes(), writer);
223             }
224         } else if (node instanceof CharacterData JavaDoc) {
225             if (!(node instanceof Comment)) {
226                 writer.write(node.getNodeValue());
227             }
228         } else if (node instanceof Document) {
229             if (logger.isInfoEnabled()) logger.info("Writing document: "+node.getClass());
230             writeAll(node.getChildNodes(), writer);
231         } else if (node instanceof DocumentType) {
232             String JavaDoc name = node.getNodeName();
233             if (!name.equals(DOCUMENT_TYPE)) {
234                 throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Document type not supported; required \""+DOCUMENT_TYPE+"\", found \""+name+"\"");
235             }
236         } else {
237             logger.warn("Unrecognized node type: "+node.getClass());
238             writeAll(node.getChildNodes(), writer);
239         }
240     }
241
242     protected void writeAll(NodeList nodes, Writer writer) throws IOException, DOMException {
243         int len = nodes.getLength();
244         for (int i = 0; i < len; i++) {
245             if (Thread.interrupted()) throw new IOException("Thread interrupted while generating output");
246             writeAll(nodes.item(i), writer);
247         }
248     }
249
250     protected void writeRow(NodeList nodes, Writer writer) throws IOException, DOMException {
251         StringWriter sw = new StringWriter(1000);
252         writeAll(nodes, sw);
253         sw.close();
254
255         StringBuffer JavaDoc sb = sw.getBuffer();
256         sb.setCharAt(sb.length()-1, '\n');
257         writer.write(sb.toString());
258     }
259
260     protected void writeHeader(NodeList nodes, Writer writer) throws IOException, DOMException {
261         //for now we just delegate to writeColumn()
262
writeColumn(nodes, writer);
263     }
264
265     protected void writeColumn(NodeList nodes, Writer writer) throws IOException, DOMException {
266         StringWriter sw = new StringWriter(100);
267         writeAll(nodes, sw);
268         sw.close();
269
270         String JavaDoc data = sw.toString();
271         writer.write('"');
272         writer.write(data.replaceAll("\"", "\"\""));
273         writer.write("\",");
274     }
275 }
276
Popular Tags