Hola Amigos,
Acá comparto una clase que ayuda a crear una instancia de un java DOM Document.
Estas son las características de la clase:
- Te quita todo el tedioso trabajo de hacer explícitamente el catch de las excepciones, haciendo que tu código sea mas legible y entendible.
- Las excepciones son manejadas con un solo handler, haciendo que puedas mejorar la clase aumentar varios builders y manejar las excepciones en un solo método.
- También pueden apreciar que la instancia del DocumentBuilderFactory es inicializado estáticamente.
Luego mas abajo podrán ver las pruebas de unidad con solo casos mas simple y el manejo de una excepción.
Si desean bajar el código, este esta disponible en: https://github.com/rhuanca/XMLUtilities
package renidev.utils.xml; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * This class helps to create a instance of a DOM document instance * simplifying the way to create it. * @author Renan Huanca */ public class SimpleDocumentBuilder { private static DocumentBuilder documentBuilder; static { try { documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new RuntimeException("Unable to get document builder. - "+ e.getMessage(), e); } } /** * Allow to create a DOM Document instance with the given parameter. * * @param xml * @return */ public static Document buildDocument(String xml) { Document doc = null; try { doc = documentBuilder.parse(new ByteArrayInputStream(xml.getBytes())); } catch (Exception e) { handleException(e); } return doc; } /** * Allow to create a DOM Document instance with the given parameter. * @param stream * @return */ public static Document buildDocument(InputStream stream) { Document doc = null; try { doc = documentBuilder.parse(stream); } catch (Exception e) { handleException(e); } return doc; } public static void handleException(Exception e){ if(e instanceof IOException) { throw new RuntimeException("Unable to read xml - " + e.getMessage(), e); } else if (e instanceof SAXParseException) { SAXParseException exception = (SAXParseException) e; throw new RuntimeException("Unable to parse xml - Line: " + exception.getLineNumber() + " - " + e.getMessage(), e); } else if ( e instanceof SAXException) { throw new RuntimeException("Unable to parse xml - " + e.getMessage(), e); } else { throw new RuntimeException(e); } } } |
package renidev.utils.xml; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Node; import static org.junit.Assert.*; public class SimpleDocumentBuilderTest { @Test public void one_node(){ String xml = "<data>hello world</data>"; Document doc = SimpleDocumentBuilder.buildDocument(xml); Node dataNode = doc.getFirstChild(); assertEquals(1, dataNode.getChildNodes().getLength()); assertEquals("hello world", dataNode.getTextContent()); } @Test public void one_level(){ String xml = "<data><child>hello world</child></data>"; Document doc = SimpleDocumentBuilder.buildDocument(xml); Node dataNode = doc.getFirstChild(); assertEquals(1, dataNode.getChildNodes().getLength()); assertEquals("hello world", dataNode.getFirstChild().getTextContent()); } @Test public void test_exception(){ String xml = "<data>hello world<data>"; try { @SuppressWarnings("unused") Document doc = SimpleDocumentBuilder.buildDocument(xml); } catch (RuntimeException e) { assertEquals("Unable to parse xml - Line: 1 - XML document structures must start and end within the same entity.", e.getMessage()); return; } fail("No exception was throw"); } } |