001/* 002 * BioJava development code 003 * 004 * This code may be freely distributed and modified under the 005 * terms of the GNU Lesser General Public Licence. This should 006 * be distributed with the code. If you do not have a copy, 007 * see: 008 * 009 * http://www.gnu.org/copyleft/lesser.html 010 * 011 * Copyright for this code is held jobytely by the individual 012 * authors. These should be listed in @author doc comments. 013 * 014 * For more information on the BioJava project and its aims, 015 * or to join the biojava-l mailing list, visit the home page 016 * at: 017 * 018 * http://www.biojava.org/ 019 * 020 */ 021 022package org.biojava.utils.stax; 023 024import org.xml.sax.Attributes; 025import org.xml.sax.SAXException; 026 027/** 028 * <p> 029 * StAX handler for any element which just contains a string representation of 030 * a byte. 031 * </p> 032 * 033 * <p> 034 * This calss collects the string data, and when it is complete, passes it to 035 * the (abstract) setByteValue method. Typical use of this class is as 036 * a base for a small (often anonymous) class which takes the byte value 037 * and stores it in some variable. 038 * </p> 039 * 040 * @author Matthew Pocock 041 * @author Greg Cox 042 * @since 1.2 043 */ 044 045public abstract class ByteElementHandlerBase extends StAXContentHandlerBase { 046 private int level = 0; 047 private StringBuffer data = new StringBuffer(); 048 049 public void startElement( 050 String nsURI, 051 String localName, 052 String qName, 053 Attributes attrs, 054 DelegationManager dm 055 ) throws SAXException { 056 level++; 057 if (level > 1) { 058 throw new SAXException("Found child element when expecting character data"); 059 } 060 } 061 062 public void endElement( 063 String nsURI, 064 String localName, 065 String qName, 066 StAXContentHandler handler 067 ) throws SAXException { 068 level--; 069 if (level == 0) { 070 try { 071 setByteValue(Byte.parseByte(data.substring(0))); 072 } catch (NumberFormatException nfe) { 073 throw new SAXException(nfe); 074 } 075 } 076 } 077 078 public void characters(char[] ch, int start, int end) throws SAXException { 079 data.append(ch, start, end); 080 } 081 082 /** 083 * <p> 084 * Override this method to do something useful with the 085 * byte we collect. 086 * </p> 087 * 088 * <p> 089 * This method will be invoked by endElement with the fully parsed byte. 090 * </p> 091 * 092 * @param val the fully parsed byte 093 * @throws SAXException if for any reason the byte is not palatable 094 */ 095 protected abstract void setByteValue(byte val) throws SAXException; 096}