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 jobooleanly 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 * an boolean.
031 * </p>
032 *
033 * <p>
034 * This calss collects the string data, and when it is complete, passes it to
035 * the (abstract) setBooleanValue method.  Typical use of this class is as
036 * a base for a small (often anonymous) class which takes the boolean 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 BooleanElementHandlerBase 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      setBooleanValue("true".equals(data.substring(0)));
071    }
072  }
073
074  public void characters(char[] ch, int start, int end) throws SAXException {
075    data.append(ch, start, end);
076  }
077
078  /**
079   * <p>
080   * Override this method to do something useful with the
081   * boolean we collect.
082   * </p>
083   *
084   * <p>
085   * This method will be invoked by endElement with the fully parsed boolean.
086   * </p>
087   *
088   * @param val  the fully parsed boolean
089   * @throws SAXException if for any reason the boolean is not palatable
090   */
091  protected abstract void setBooleanValue(boolean val) throws SAXException;
092}