PageRenderTime 75ms CodeModel.GetById 62ms app.highlight 9ms RepoModel.GetById 1ms app.codeStats 1ms

/src/org/mt4j/util/xml/XmlHandler.java

http://mt4j.googlecode.com/
Java | 266 lines | 136 code | 42 blank | 88 comment | 9 complexity | 275d1c6a9e573c1303519120316dec59 MD5 | raw file
  1/***********************************************************************
  2 * mt4j Copyright (c) 2008 - 2009 C.Ruff, Fraunhofer-Gesellschaft All rights reserved.
  3 *  
  4 *   This program is free software: you can redistribute it and/or modify
  5 *   it under the terms of the GNU General Public License as published by
  6 *   the Free Software Foundation, either version 3 of the License, or
  7 *   (at your option) any later version.
  8 *
  9 *   This program 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
 12 *   GNU General Public License for more details.
 13 *
 14 *   You should have received a copy of the GNU General Public License
 15 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 16 *
 17 ***********************************************************************/
 18package org.mt4j.util.xml;
 19
 20import java.io.ByteArrayInputStream;
 21import java.io.File;
 22import java.io.FileOutputStream;
 23import java.io.IOException;
 24import java.io.InputStream;
 25
 26import javax.xml.parsers.DocumentBuilder;
 27import javax.xml.parsers.DocumentBuilderFactory;
 28import javax.xml.parsers.ParserConfigurationException;
 29import javax.xml.parsers.SAXParser;
 30import javax.xml.parsers.SAXParserFactory;
 31
 32import org.w3c.dom.Document;
 33import org.xml.sax.EntityResolver;
 34import org.xml.sax.InputSource;
 35import org.xml.sax.SAXException;
 36import org.xml.sax.helpers.DefaultHandler;
 37
 38import com.sun.org.apache.xml.internal.serialize.OutputFormat;
 39import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
 40
 41/**
 42 * The Class XmlHandler.
 43 * 
 44 * @author Christopher Ruff
 45 */
 46public class XmlHandler {
 47	
 48	/** The xml handler. */
 49	private static XmlHandler xmlHandler = null;
 50	
 51	/** The name space aware. */
 52	private boolean nameSpaceAware;
 53	
 54	/** The validatig. */
 55	private boolean validatig;
 56	
 57	/**
 58	 * Instantiates a new xml handler.
 59	 */
 60	private XmlHandler(){
 61		nameSpaceAware = false;
 62		validatig = false;
 63	}
 64
 65	/**
 66	 * Gets the single instance of XmlHandler.
 67	 * 
 68	 * @return single instance of XmlHandler
 69	 */
 70	public static XmlHandler getInstance(){
 71		if (xmlHandler == null){
 72			xmlHandler = new XmlHandler();
 73			return xmlHandler;
 74		}else
 75			return xmlHandler;
 76	}
 77	
 78	
 79	/**
 80	 * loads a xml file into memory and returns a document object.
 81	 * 
 82	 * @param file the file
 83	 * 
 84	 * @return the document
 85	 */
 86	public Document load(File file) {
 87		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 88		Document document = null;
 89		
 90		factory.setValidating(validatig); 
 91		factory.setNamespaceAware(nameSpaceAware); 
 92		
 93		try {
 94			DocumentBuilder builder = factory.newDocumentBuilder();
 95			document = builder.parse(file);
 96			System.out.println("--> Parsed the xml file : " + file);
 97		} catch (SAXException sxe) {
 98			// Error generated during parsing
 99			Exception x = sxe;
100			if (sxe.getException() != null)
101				x = sxe.getException();
102			x.printStackTrace();
103
104		} catch (ParserConfigurationException pce) {
105			// Parser with specified options can't be built
106			pce.printStackTrace();
107
108		} catch (IOException ioe) {
109			// I/O error
110			ioe.printStackTrace();
111		}
112				
113		return document;
114	}
115
116	/**
117	 * This method writes a DOM document to a file.
118	 * 
119	 * @param doc the doc
120	 * @param file the file
121	 * 
122	 * @return true, if write xml file
123	 */
124	public boolean writeXmlFile(Document doc, File file) {
125		try {
126			FileOutputStream fileOut = new FileOutputStream(file);
127			OutputFormat format 	 = new OutputFormat(doc);
128	        format.setLineWidth(900);
129	        format.setIndenting(true);
130	        format.setIndent(6);
131	        format.setOmitComments(false);
132	        
133			XMLSerializer serializer = new XMLSerializer(fileOut, format); 
134			serializer.serialize(doc);
135			
136			fileOut.close();
137			System.out.println("Wrote the content of the document into the file: " + file);
138		} catch (IOException e) {
139			e.printStackTrace();
140			return false;
141		} 
142		return true;
143	}
144	
145	
146	/**
147	 * parses an xml file with the SaxParser and uses the provided
148	 * defaulthandler to process the input.
149	 * 
150	 * @param defaultHandler the default handler
151	 * @param filePath the file path
152	 */
153	public void saxParse(String filePath, DefaultHandler defaultHandler){
154	 	SAXParserFactory spf = SAXParserFactory.newInstance();
155	 	
156	 	spf.setValidating(validatig);
157	 	spf.setNamespaceAware(nameSpaceAware);
158	 	
159	       try{
160	    	   //Dont parse external dtd, so we dont have to connect to http etc
161	    	   spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); 
162	    	   
163		       SAXParser parser = spf.newSAXParser();
164		       
165		       parser.getXMLReader().setEntityResolver(new EntityResolver(){
166					public InputSource resolveEntity(String arg0, String arg1) throws SAXException, IOException {
167						return new InputSource(new ByteArrayInputStream(new byte[0]));
168					}
169		        });
170		       
171		       File file = new File(filePath);
172		       if (file.exists()){
173		    	   parser.parse(new File(filePath), defaultHandler);
174		       }else{
175		    	   InputStream in = null;
176		    	   in = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
177		    	   if (in == null){
178		    		   in = getClass().getResourceAsStream(filePath);
179		    	   }
180		    	   parser.parse(in, defaultHandler);
181		       }
182	       }
183	       catch (Exception e){
184	           System.err.println("Error while parsing! : " + filePath);
185	          e.printStackTrace();
186	       }
187	}
188	
189	/**
190	 * parses an xml file with the SaxParser and uses the provided
191	 * defaulthandler to process the input.
192	 * 
193	 * @param defaultHandler the default handler
194	 * @param string the string
195	 */
196	public void saxParseString(String string, DefaultHandler defaultHandler){
197	 	SAXParserFactory spf = SAXParserFactory.newInstance();
198	 	
199	 	spf.setValidating(validatig);
200	 	spf.setNamespaceAware(nameSpaceAware);
201	 	
202	 	byte stringAsByteArray[] = string.getBytes();
203	 	ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(stringAsByteArray);
204	 	
205	       try{
206		       SAXParser parser = spf.newSAXParser();
207		       
208		       parser.getXMLReader().setEntityResolver(new EntityResolver(){
209					public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
210//						return new InputSource(new ByteArrayInputStream(new byte[0]));
211						if (systemId.endsWith(".dtd"))
212						      // this deactivates all DTDs by giving empty XML docs
213						      return new InputSource(new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes()));
214						    else return null;
215					}
216		        });
217		       
218		       parser.parse(byteArrayInputStream, defaultHandler);
219	       }
220	       catch (Exception e){
221	           System.err.println("Error while parsing!");
222	           System.err.println(e);
223	       }
224	}
225
226	
227	
228	/**
229	 * Checks if is name space aware.
230	 * 
231	 * @return true, if is name space aware
232	 */
233	public boolean isNameSpaceAware() {
234		return nameSpaceAware;
235	}
236
237	/**
238	 * Sets the name space aware.
239	 * 
240	 * @param nameSpaceAware the new name space aware
241	 */
242	public void setNameSpaceAware(boolean nameSpaceAware) {
243		this.nameSpaceAware = nameSpaceAware;
244	}
245
246	/**
247	 * Checks if is validatig.
248	 * 
249	 * @return true, if is validatig
250	 */
251	public boolean isValidatig() {
252		return validatig;
253	}
254
255	/**
256	 * Sets the validatig.
257	 * 
258	 * @param validatig the new validatig
259	 */
260	public void setValidatig(boolean validatig) {
261		this.validatig = validatig;
262	}
263	
264	
265	
266}