KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > mvnforum > admin > importexport > XMLWriter


1 /*
2  * $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/admin/importexport/XMLWriter.java,v 1.6 2006/04/14 17:36:29 minhnn Exp $
3  * $Author: minhnn $
4  * $Revision: 1.6 $
5  * $Date: 2006/04/14 17:36:29 $
6  *
7  * ====================================================================
8  *
9  * Copyright (C) 2002-2006 by MyVietnam.net
10  *
11  * All copyright notices regarding mvnForum MUST remain
12  * intact in the scripts and in the outputted HTML.
13  * The "powered by" text/logo with a link back to
14  * http://www.mvnForum.com and http://www.MyVietnam.net in
15  * the footer of the pages MUST remain visible when the pages
16  * are viewed on the internet or intranet.
17  *
18  * This program is free software; you can redistribute it and/or modify
19  * it under the terms of the GNU General Public License as published by
20  * the Free Software Foundation; either version 2 of the License, or
21  * any later version.
22  *
23  * This program is distributed in the hope that it will be useful,
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26  * GNU General Public License for more details.
27  *
28  * You should have received a copy of the GNU General Public License
29  * along with this program; if not, write to the Free Software
30  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
31  *
32  * Support can be obtained from support forums at:
33  * http://www.mvnForum.com/mvnforum/index
34  *
35  * Correspondence and Marketing Questions can be sent to:
36  * info at MyVietnam net
37  *
38  * @author: Igor Manic
39  */

40 package com.mvnforum.admin.importexport;
41
42 import java.io.*;
43
44 import org.apache.commons.logging.Log;
45 import org.apache.commons.logging.LogFactory;
46 import net.myvietnam.mvncore.exception.ExportException;
47
48 /**
49  * @author Igor Manic
50  * @version $Revision: 1.6 $, $Date: 2006/04/14 17:36:29 $
51  * <br/>
52  * <code>XMLWriter</code> class encapsulates methods for creating and writing
53  * data to XML files with automatic indentation and special characters encoding.
54  */

55 public class XMLWriter {
56
57     /** Message log. */
58     private static Log log = LogFactory.getLog(XMLWriter.class);
59
60     private static String JavaDoc lineSeparator=System.getProperty("line.separator", "\n");
61     private StringBuffer JavaDoc textBuffer;
62     private int indentLevel=0; //current XML element level
63
private String JavaDoc indentString=""; //indent string for each next level of XML output
64
private OutputStreamWriter outWriter=null;
65     private boolean startedNewElement=false;
66
67     private XMLWriter() {
68         super();
69         textBuffer=null;
70         indentLevel=0; indentString="";
71         outWriter=null;
72         startedNewElement=false;
73     }
74
75     public XMLWriter(String JavaDoc indentString, OutputStreamWriter outWriter) {
76         this();
77         this.indentString=indentString;
78         this.outWriter=outWriter;
79     }
80
81     public XMLWriter(String JavaDoc indentString, File outputFile)
82     throws ExportException {
83         this();
84         this.indentString=indentString;
85         log.debug("Setting output to file \""+outputFile.getAbsolutePath()+"\"");
86         if (!outputFile.exists())
87             try {
88                 outputFile.createNewFile();
89             } catch (IOException e) {
90                 log.error("XML output could not be created.");
91                 throw new ExportException("Error on server: "+
92                       "Can't make XML output file.", e);
93             }
94         else if (!outputFile.isFile()) {
95             log.error("XML output is not a file (it's probably directory).");
96             throw new ExportException("Error on server: "+
97                   "XML output is not a file (it's probably directory).");
98         }
99         if (!outputFile.canWrite()) {
100             log.error("XML output file can't be written to.");
101             throw new ExportException("Error on server: "+
102                   "XML output file can't be written to.");
103         } else {
104             try {
105                 java.io.OutputStream JavaDoc outStream=new FileOutputStream(outputFile);
106                 this.outWriter=new OutputStreamWriter(outStream, "UTF8");
107             } catch (FileNotFoundException e) {
108                 log.error("XML output file can't be found.");
109                 throw new ExportException("Error on server: "+
110                       "XML output file can't be found.", e);
111             } catch (UnsupportedEncodingException e) {
112                 log.error("UTF8 is unsupported encoding for XML output.");
113                 throw new ExportException("Error on server: "+
114                       "Can't make XML output file.", e);
115             }
116         }
117     }
118
119     public XMLWriter(String JavaDoc indentString, String JavaDoc fileName)
120     throws ExportException {
121         this(indentString, new File(fileName));
122     }
123
124
125     public void close() throws IOException {
126         outputFlush();
127         if (outWriter!=null) outWriter.close();
128     }
129
130     public void startDocument(String JavaDoc dtdschemaDecl) throws IOException {
131         String JavaDoc xmlDecl="<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
132         startedNewElement=false;
133         outputText(xmlDecl); outputNewLine();
134         outputText(dtdschemaDecl); outputNewLine();
135     }
136
137     public void endDocument() throws IOException {
138         processBufferedData();
139         outputNewLine();
140         outputFlush();
141     }
142
143     public void startElement(String JavaDoc elementName)
144     throws IOException {
145         startElement(elementName, null);
146     }
147
148     public void startElement(String JavaDoc elementName, String JavaDoc[] attrNameValue)
149     throws IOException {
150         processBufferedData();
151         outputNewLine();
152         outputText("<"+elementName);
153         if (attrNameValue!=null) for (int i=0; i<attrNameValue.length-1; i+=2) {
154             String JavaDoc attrName=attrNameValue[i];
155             String JavaDoc attrValue=attrNameValue[i+1];
156             outputText(" ");
157             outputText(attrName+"=\""+attrValue+"\"");
158         }
159         outputText(">");
160         indentLevel++;
161         //outputNewLine();
162
startedNewElement=true;
163     }
164
165     public void endElement(String JavaDoc elementName)
166     throws IOException {
167         processBufferedData();
168         indentLevel--;
169         if (!startedNewElement) outputNewLine();
170         outputText("</"+elementName+">");
171         //outputNewLine();
172
startedNewElement=false;
173     }
174
175
176     public void writeNewLine() throws IOException {
177         outputNewLine();
178     }
179
180     public void writeComment(String JavaDoc comment) throws IOException {
181         processBufferedData();
182         /*if (startedNewElement)*/ outputNewLine();
183         outputText("<!-- "+comment+" -->");
184         //startedNewElement=false; I should leave this variable, otherwise, if
185
//I have more comments one behind another, they'll all be output in
186
//one row, one to another, which is bad
187
}
188
189     public void writeData(String JavaDoc data) throws IOException {
190         if (textBuffer==null) {
191             textBuffer=new StringBuffer JavaDoc(data);
192         } else {
193             textBuffer.append(data);
194         }
195     }
196
197     public void encodeAndWriteData(String JavaDoc data) throws IOException {
198         //we should encode all '<' and '&'
199
int amp=data.indexOf('&');
200         int lt=data.indexOf('<');
201         int i=-1;
202         if ((amp>=0) && (lt>=0)) i=(amp<lt)?amp:lt;
203         else if (amp>=0) i=amp;
204         else i=lt;
205         while ((i<data.length()) && (i>=0)) {
206             if (i==amp) {
207                 data=data.substring(0, i)+"&amp;"+data.substring(i+1);
208                 amp=data.indexOf('&', i+4);
209                 lt=data.indexOf('<', i+4);
210                 i+=4; //it should be 5, but nevermind
211
} else if (i==lt) {
212                 data=data.substring(0, i)+"&lt;"+data.substring(i+1);
213                 amp=data.indexOf('&', i+3);
214                 lt=data.indexOf('<', i+3);
215                 i+=3; //it should be 5, but nevermind
216
} else {
217                 log.error("processBufferedRawText(): i=="+i+
218                           " is different than both amp=="+amp+" and lt=="+lt+"?!");
219                 i++;
220                 amp=data.indexOf('&', i);
221                 lt=data.indexOf('<', i);
222             }
223             if ((amp>=0) && (lt>=0)) i=(amp<lt)?amp:lt;
224             else if (amp>=0) i=amp;
225             else i=lt;
226         }
227
228         writeData(data);
229     }
230
231
232
233 // ========================================================
234
// =================== RAW TEXT OUTPUT ====================
235
// ========================================================
236

237     private void processBufferedData() throws IOException {
238         if (textBuffer==null) return;
239         String JavaDoc s=""+textBuffer;
240         if (!s.trim().equals("")) textBuffer=null;
241         if (s.equals("")) return;
242
243         if (startedNewElement) outputNewLine();
244         startedNewElement=false;
245         String JavaDoc padding="";
246         for (int i=0; i<indentLevel; i++) padding=padding+indentString;
247         int pos=s.indexOf(lineSeparator);
248         while ((pos<s.length()) && (pos>=0)) {
249             s=s.substring(0, pos)+
250               lineSeparator+ padding+
251               s.substring(pos+lineSeparator.length());
252             pos=s.indexOf(lineSeparator, pos+lineSeparator.length());
253         }
254         outputText(s);
255     }
256
257     private void outputText(String JavaDoc s) throws IOException {
258         if (outWriter==null) {
259             log.error("outputText(): outWriter==null.");
260         } else {
261             outWriter.write(s);
262         }
263     }
264
265     private void outputFlush() throws IOException {
266         if (outWriter==null) {
267             log.error("outputFlush(): outWriter==null.");
268         } else {
269             outWriter.flush();
270         }
271     }
272
273     private void outputNewLine() throws IOException {
274         if (outWriter==null) {
275             log.error("outputNewLine(): outWriter==null.");
276         } else {
277             outWriter.write(lineSeparator);
278             for (int i=0; i<indentLevel; i++) outWriter.write(indentString);
279         }
280     }
281
282
283 }
284
285
Free Books   Free Magazines  
Popular Tags