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 jointly 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 * StAX handler for any element which just contains a string. This class 029 * collects the string data, and when it is complete, passes it to the 030 * (abstract) setStringValue method. Typical use of this class is as 031 * a base for a small (often anonymous) class which takes the string value 032 * and stores it in some variable. 033 * 034 * @author Thomas Down 035 * @author Greg Cox 036 * @since 1.2 037 */ 038 039public abstract class StringElementHandlerBase extends StAXContentHandlerBase { 040 private int level = 0; 041 private StringBuffer data = new StringBuffer(); 042 043 044 public void startElement(String nsURI, 045 String localName, 046 String qName, 047 Attributes attrs, 048 DelegationManager dm) 049 throws SAXException 050 { 051 level++; 052 if (level > 1) { 053 throw new SAXException("Found child element when expecting character data"); 054 } 055 } 056 057 public void endElement(String nsURI, 058 String localName, 059 String qName, 060 StAXContentHandler handler) 061 throws SAXException 062 { 063 level--; 064 if (level == 0) { 065 setStringValue(data.substring(0)); 066 } 067 } 068 069 public void characters(char[] ch, int start, int length) 070 throws SAXException 071 { 072 data.append(ch, start, length); 073 } 074 075 /** 076 * Override this method to do something useful with the 077 * string we collect. Maybe we should do this by delegation 078 * rather than extension. 079 */ 080 081 protected abstract void setStringValue(String s) throws SAXException; 082}