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 jocharly 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 char.
031 * </p>
032 *
033 * <p>
034 * This calss collects the string data, and when it is complete, passes it to
035 * the (abstract) setCharValue method.  Typical use of this class is as
036 * a base for a small (often anonymous) class which takes the char value
037 * and stores it in some variable.
038 * </p>
039 *
040 * @author Matthew Pocock
041 * @since 1.2
042 */
043
044public abstract class CharElementHandlerBase extends StAXContentHandlerBase {
045  private int level = 0;
046  private StringBuffer data = new StringBuffer();
047
048  public void startElement(
049    String nsURI,
050    String localName,
051    String qName,
052    Attributes attrs,
053    DelegationManager dm
054  ) throws SAXException {
055    level++;
056    if (level > 1) {
057      throw new SAXException("Found child element when expecting character data");
058    }
059  }
060
061  public void endElement(
062    String nsURI,
063    String localName,
064    String qName,
065    StAXContentHandler handler
066  ) throws SAXException {
067    level--;
068    if (level == 0) {
069      if(data.length() != 1) {
070        throw new SAXException(
071          "Expecting single character. Got '" + data + "'"
072        );
073      } else {
074        setCharValue(data.charAt(0));
075      }
076    }
077  }
078  
079  public void characters(char[] ch, int start, int end) throws SAXException {
080    data.append(ch, start, end);
081  }
082
083  /**
084   * <p>
085   * Override this method to do something useful with the
086   * char we collect.
087   * </p>
088   *
089   * <p>
090   * This method will be invoked by endElement with the fully parsed char.
091   * </p>
092   *
093   * @param val  the fully parsed char
094   * @throws SAXException if for any reason the char is not palatable
095   */
096  protected abstract void setCharValue(char val) throws SAXException;
097}