1 package com.thaiopensource.validate.schematron; 2 3 import org.xml.sax.helpers.DefaultHandler ; 4 import org.xml.sax.ErrorHandler ; 5 import org.xml.sax.SAXParseException ; 6 import org.xml.sax.SAXException ; 7 import org.xml.sax.Attributes ; 8 import com.thaiopensource.util.Localizer; 9 10 class OutputHandler extends DefaultHandler { 11 private final ErrorHandler eh; 12 private int lineNumber = -1; 13 private String systemId = null; 14 private final StringBuffer message = new StringBuffer (); 15 private boolean inMessage = false; 16 private final String lineSeparator; 17 private static final String indent = " "; 18 private final Localizer localizer = new Localizer(OutputHandler.class); 19 20 OutputHandler(ErrorHandler eh) { 21 this.eh = eh; 22 this.lineSeparator = System.getProperty("line.separator"); 23 } 24 25 public void characters(char ch[], int start, int length) 26 throws SAXException { 27 if (inMessage) { 28 for (int i = 0; i < length; i++) { 29 char c = ch[start + i]; 30 switch (c) { 31 case ' ': 32 case '\r': 33 case '\n': 34 case '\t': 35 if (message.length() == 0 || message.charAt(message.length() - 1) != ' ') 36 message.append(' '); 37 break; 38 default: 39 message.append(c); 40 break; 41 } 42 } 43 } 44 } 45 46 public void ignorableWhitespace(char ch[], int start, int length) 47 throws SAXException { 48 characters(ch, start, length); 49 } 50 51 public void startElement(String uri, String localName, 52 String qName, Attributes attributes) 53 throws SAXException { 54 if (localName.equals("failed-assertion") 55 || localName.equals("report")) { 56 String value = attributes.getValue("", "line-number"); 57 if (value == null) 58 lineNumber = -1; 59 else { 60 try { 61 lineNumber = Integer.parseInt(value); 62 } 63 catch (NumberFormatException e) { 64 lineNumber = -1; 65 } 66 } 67 value = attributes.getValue("", "system-id"); 68 if (value != null && value.equals("")) 69 value = null; 70 systemId = value; 71 message.append(localizer.message(localName.equals("failed-assertion") 72 ? "failed_assertion" 73 : "report")); 74 } 75 else if (localName.equals("statement") || localName.equals("diagnostic")) { 76 inMessage = true; 77 message.append(lineSeparator); 78 message.append(indent); 79 } 80 } 81 82 public void endElement(String uri, String localName, String qName) 83 throws SAXException { 84 if (localName.equals("statement") || localName.equals("diagnostic")) { 85 if (message.length() > 0 && message.charAt(message.length() - 1) == ' ') 86 message.setLength(message.length() - 1); 87 inMessage = false; 88 } 89 else if (localName.equals("failed-assertion") 90 || localName.equals("report")) { 91 eh.error(new SAXParseException (message.toString(), null, systemId, lineNumber, -1)); 92 message.setLength(0); 93 } 94 } 95 } 96 | Popular Tags |