KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * Copyright (C) 2001 Christian Cryder [christianc@granitepeaks.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: DefaultDOMWriter.java,v 1.21 2004/02/02 22:15:02 shawnw Exp $
19  */

20 package org.enhydra.barracuda.core.util.dom;
21
22 import java.io.*;
23 import javax.servlet.*;
24 import javax.servlet.http.*;
25
26 import org.apache.log4j.*;
27
28 import org.w3c.dom.*;
29 import org.w3c.dom.html.*;
30
31 import org.w3c.tidy.Tidy;
32
33 import org.enhydra.barracuda.core.comp.*;
34 import org.enhydra.xml.io.*;
35
36
37 /**
38  * This class provides the default implementation for writing a DOM.
39  * XMLC is used for formatting the dom. Besides output options features
40  * supplied by XMLC, supported features include pretty printing and preventing
41  * page caching (which prevents any redisplay of the page even via the back
42  * button) or setting a max-age (which generally allows for redisplay of a
43  * page via the back button, but not when revisiting the URL). So, the prevent
44  * caching and max age features are mutually exclusive. Default behavior is for
45  * default output options (obtained automatically from the current document),
46  * no pretty printing, and setting a max-age header of 0 (zero). Defaults may
47  * be modified via class static variables or overridden explicitly via
48  * constructors and/or mutators.
49  */

50 public class DefaultDOMWriter implements DOMWriter {
51
52     protected static final Logger logger = Logger.getLogger(DefaultDOMWriter.class.getName());
53
54     //csc_111103_1 - added
55
/**
56      * default OutputOptions public id (ie. "-//W3C//DTD HTML 4.01 Transitional//EN"); if
57      * set, the default output options will use this value
58      */

59     public static String JavaDoc DEFAULT_OO_PUBLIC_ID = null;
60
61     //csc_111103_1 - added
62
/**
63      * default OutputOptions system id (ie. "http://www.w3.org/TR/html401/loose.dtd"); if
64      * set, the default output options will use this value
65      */

66     public static String JavaDoc DEFAULT_OO_SYSTEM_ID = null;
67
68     /**
69      * default value for pretty printing, false unless modified at runtime
70      */

71     public static boolean DEFAULT_PRINT_PRETTY = false;
72
73     /**
74      * default value for preventing caching, false unless modified at runtime
75      */

76     public static boolean DEFAULT_PREVENT_CACHING = false;
77
78     /**
79      * default value for max age of rendered page, 0 (zero) unless modified at runtime
80      */

81     public static int DEFAULT_MAX_AGE = 0;
82
83     protected DOMFormatter dfm = null;
84     protected OutputOptions oo = null;
85     protected String JavaDoc contentType = null; //csc_012804_1
86
protected String JavaDoc contentDisposition = null; //csc_012804_1
87
protected boolean printPretty = false;
88     protected boolean preventCaching = false;
89     protected boolean leaveWriterOpen = false;
90     protected int maxAge = 0; //csc_061202.1 - added
91

92     /**
93      * Default constructor
94      */

95     public DefaultDOMWriter() {
96         this(null, DEFAULT_PRINT_PRETTY, DEFAULT_PREVENT_CACHING, DEFAULT_MAX_AGE);
97     }
98
99     /**
100      * Public constructor. Allows you to specify OutputOptions.
101      *
102      * @param oo OutputOptions to specify how the DOM should be formatted
103      */

104     public DefaultDOMWriter(OutputOptions oo) {
105         this(oo, DEFAULT_PRINT_PRETTY, DEFAULT_PREVENT_CACHING, DEFAULT_MAX_AGE);
106     }
107
108     /**
109      * Public constructor. Allows you to specify pretty printing.
110      *
111      * @param printPretty true if pretty print
112      */

113     public DefaultDOMWriter(boolean printPretty) {
114         this(null, printPretty, DEFAULT_PREVENT_CACHING, DEFAULT_MAX_AGE);
115     }
116
117     /**
118      * Public constructor. Allows you to specify output options,
119      * pretty printing and whether or not the page should be cached or the
120      * max-age header for the page (how many seconds until it expires).
121      * Note that the latter two options are mutually exclusive.
122      *
123      * @param ioo OutputOptions to specify how the DOM should be formatted, may be null
124      * @param iprintPretty true if pretty print
125      * @param ipreventCaching true if we want to prevent client side caching of the page
126      * @param imaxAge how many seconds until the page should expire
127      */

128     public DefaultDOMWriter(OutputOptions ioo, boolean iprintPretty, boolean ipreventCaching, int imaxAge) {
129         setOutputOptions(ioo);
130         setPrettyPrint(iprintPretty);
131         setPreventCaching(ipreventCaching);
132         setMaxAge(imaxAge);
133     }
134
135 //csc_012804_1_start
136
/**
137      * Set the content type (defaults to "text/html" or "text/xml" depending on the
138      * document type
139      */

140     public void setContentType(String JavaDoc icontentType) {
141         contentType = icontentType;
142     }
143
144     /**
145      * Get the content type
146      */

147     public String JavaDoc getContentType() {
148         return contentType;
149     }
150
151     /**
152      * Set the content disposition (ie. "inline; filename=foo.txt", defaults to null)
153      */

154     public void setContentDisposition(String JavaDoc icontentDisposition) {
155         contentDisposition = icontentDisposition;
156     }
157
158     /**
159      * Get the content disposition
160      */

161     public String JavaDoc getContentDisposition() {
162         return contentDisposition;
163     }
164
165     /**
166      * Set true if we want to leave the writer open (ie. for multiple writes)
167      */

168     public void setLeaveWriterOpen(boolean val) {
169         leaveWriterOpen = val;
170     }
171
172     /**
173      * return true if the writer is configured to leave the output stream open
174      */

175     public boolean getLeaveWriterOpen() {
176         return leaveWriterOpen;
177     }
178
179     /**
180      * Prepare the response object
181      *
182      * @param node the DOM node to be written out
183      * @param resp the HttpServletResponse object
184      */

185     public void prepareResponse(HttpServletResponse resp) throws IOException {
186         //set the content type and disposition
187
if (logger.isDebugEnabled()) logger.debug("Setting content type:"+contentType+" content disposition:"+contentDisposition);
188         if (contentType!=null) resp.setContentType(contentType);
189         if (contentDisposition!=null) resp.setHeader("Content-Disposition", contentDisposition);
190
191         //if we need to prevent caching
192
if (preventCaching) {
193             //add the appropriate headers to the response
194
if (logger.isDebugEnabled()) logger.debug("updating resp hdr to prevent caching");
195             resp.setHeader("Pragma","no-cache");
196             resp.setHeader("Cache-Control","no-cache");
197             resp.setDateHeader("Expires", System.currentTimeMillis());
198
199         //otherwise explicitly give it a max-age (this will generally allow browsers like
200
//IE to page back in history without reloading, but if the user actually revisits the
201
//URL, then it will still be reloaded)
202
} else {
203             resp.setHeader("Cache-Control","max-age="+maxAge);
204             resp.setDateHeader("Last-Modified", System.currentTimeMillis());
205         }
206     }
207 //csc_012804_1_end
208

209     /**
210      * Write a DOM to a ServletResponse object. This method will
211      * automatically set the content type for you.
212      *
213      * @param node the DOM node to be written out
214      * @param resp the HttpServletResponse object
215      */

216     public void write(Node node, HttpServletResponse resp) throws IOException {
217 //csc_012804_1_start
218
/*
219         //set the response type (TODO:need to support WML as well)
220         String responseType = "text/xml";
221         if (node instanceof HTMLDocument) responseType = "text/html";
222         if (logger.isDebugEnabled()) logger.debug("Setting the response type:"+responseType);
223         resp.setContentType(responseType);
224
225         //if we need to prevent caching
226         if (preventCaching) {
227             //add the appropriate headers to the response
228             if (logger.isDebugEnabled()) logger.debug("updating resp hdr to prevent caching");
229             resp.setHeader("Pragma","no-cache");
230             resp.setHeader("Cache-Control","no-cache");
231             resp.setDateHeader("Expires", System.currentTimeMillis());
232
233         //csc_061202.1 - added
234         //otherwise explicitly give it a max-age (this will generally allow browsers like
235         //IE to page back in history without reloading, but if the user actually revisits the
236         //URL, then it will still be reloaded)
237         } else {
238             resp.setHeader("Cache-Control","max-age="+maxAge);
239             resp.setDateHeader("Last-Modified", System.currentTimeMillis());
240         }
241 */

242         if (getContentType()==null) setContentType((node instanceof HTMLDocument) ? "text/html" : "text/xml");
243         prepareResponse(resp);
244 //csc_012804_1_end
245

246         //write the dom
247
write(node, resp.getWriter());
248     }
249
250     /**
251      * Write a DOM to an OutputStream.
252      *
253      * @param node the DOM node to be written out
254      * @param out the OutputStream to be written to
255      */

256     public void write(Node node, OutputStream out) throws IOException {
257         write(node, new PrintWriter(out));
258     }
259
260     /**
261      * Write a DOM to a Writer.
262      *
263      * @param node the DOM node to be written out
264      * @param writer the writer to be written to
265      */

266     public void write(Node node, Writer writer) throws IOException {
267         //build the default DOMFormatter if necessary
268
if (dfm==null) dfm = new DOMFormatter();
269
270         OutputOptions localoo = null;
271         //set the default output options if necessary
272
if (oo != null) localoo = oo;
273         if (localoo == null) localoo = getDefaultOutputOptions(node.getOwnerDocument());
274
275         //configure the formatter
276
dfm.setOutputOptions(localoo);
277
278         //now print...
279
if (!printPretty) {
280             //write the doc directly to the writer
281
if (logger.isDebugEnabled()) logger.debug("Writing DOM directly to writer");
282             dfm.write(node, writer);
283             if (!leaveWriterOpen) writer.close();
284         } else {
285             //write the doc to a byte stream
286
byte[] bytes = dfm.toBytes(node);
287
288             //filter the byte stream to tidy
289
if (logger.isDebugEnabled()) logger.debug("Formatting for pretty print");
290             Tidy tidy = new Tidy();
291             tidy.setIndentContent(true);
292             tidy.setSpaces(2);
293             tidy.setQuiet(true);
294             ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
295             ByteArrayOutputStream baos = new ByteArrayOutputStream();
296             tidy.parse(bais, baos);
297
298             //now write the file
299
if (logger.isDebugEnabled()) logger.debug("Writing DOM to writer");
300             writer.write(baos.toString());
301             if (!leaveWriterOpen) writer.close();
302         }
303     }
304
305     public void setPrettyPrint(boolean val) {
306         this.printPretty = val;
307     }
308
309     public void setPreventCaching(boolean val) {
310         this.preventCaching = val;
311     }
312
313     //csc_061202.1 - added
314
public void setMaxAge(int imax) {
315         this.maxAge = imax;
316     }
317
318     //jrk_20030317.1
319
public void setOutputOptions(OutputOptions ioo) {
320         this.oo = ioo;
321     }
322     
323     /**
324      * @since saw_020204_1
325      */

326     public OutputOptions getOutputOptions() {
327         return oo;
328     }
329
330     public static OutputOptions getDefaultOutputOptions(Document doc) {
331 //csc_111103_1_start
332
// return DOMFormatter.getDefaultOutputOptions(doc);
333
OutputOptions doo = DOMFormatter.getDefaultOutputOptions(doc);
334         if (DEFAULT_OO_PUBLIC_ID!=null || DEFAULT_OO_SYSTEM_ID!=null) doo.setOmitDocType(false);
335         if (DEFAULT_OO_PUBLIC_ID!=null) doo.setPublicId(DEFAULT_OO_PUBLIC_ID);
336         if (DEFAULT_OO_SYSTEM_ID!=null) doo.setSystemId(DEFAULT_OO_SYSTEM_ID);
337         return doo;
338 //csc_111103_1_end
339
}
340
341 /*
342     public static void main(String args[]) {
343         //setup
344         DOMWriter dw = new DefaultDOMWriter();
345         org.enhydra.xml.xmlc.XMLCFactory xmlcFactory = new org.enhydra.xml.xmlc.XMLCStdFactory(dw.getClass().getClassLoader(), new org.enhydra.xml.xmlc.StreamXMLCLogger());
346         org.enhydra.barracuda.tutorials.xmlc.Visibility1HTML page1 = null;
347         org.enhydra.barracuda.tutorials.xmlc.Visibility2HTML page2 = null;
348         StringWriter sw = null;
349
350         //load & print DOM page
351 System.out.println ("");
352 System.out.println ("Here 0");
353         page1 = (org.enhydra.barracuda.tutorials.xmlc.Visibility1HTML) xmlcFactory.create(org.enhydra.barracuda.tutorials.xmlc.Visibility1HTML.class);
354         page1.getElementItem2().setAttribute("visdom","false");
355         page1.getElementItem4().setAttribute("visdom","false");
356         sw = new StringWriter(5000);
357         try {
358             dw.write(page1, sw);
359         } catch (IOException e){
360             System.out.println("Error writing DOM:"+e);
361         }
362         System.out.println(sw.toString());
363
364         //load & print DOM page
365 System.out.println ("");
366 System.out.println ("Here 1");
367         page2 = (org.enhydra.barracuda.tutorials.xmlc.Visibility2HTML) xmlcFactory.create(org.enhydra.barracuda.tutorials.xmlc.Visibility2HTML.class);
368         page2.getElementItem2().setAttribute("visdom","false");
369         page2.getElementItem4().setAttribute("visdom","false");
370         sw = new StringWriter(5000);
371         try {
372             dw.write(page2, sw);
373         } catch (IOException e){
374             System.out.println("Error writing DOM:"+e);
375         }
376         System.out.println(sw.toString());
377     }
378
379 */

380
381 }
382
Popular Tags