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 jofloatly 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 representation of
029 * a float.
030 * <p>
031 * This class collects the string data, and when it is complete, passes it to
032 * the (abstract) setFloatValue method.  Typical use of this class is as
033 * a base for a small (often anonymous) class which takes the float value
034 * and stores it in some variable.
035 *
036 * @author Matthew Pocock
037 * @author Greg Cox
038 * @since 1.2
039 */
040
041public abstract class FloatElementHandlerBase extends StAXContentHandlerBase {
042  private int level = 0;
043  private StringBuffer data = new StringBuffer();
044
045  public void startElement(
046    String nsURI,
047    String localName,
048    String qName,
049    Attributes attrs,
050    DelegationManager dm
051  ) throws SAXException {
052    level++;
053    if (level > 1) {
054      throw new SAXException("Found child element when expecting character data");
055    }
056  }
057
058  public void endElement(
059    String nsURI,
060    String localName,
061    String qName,
062    StAXContentHandler handler
063  ) throws SAXException {
064    level--;
065    if (level == 0) {
066      try {
067        setFloatValue(Float.parseFloat((data.substring(0)).trim()));
068      } catch (NumberFormatException nfe) {
069        throw new SAXException(nfe);
070      }
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   * Override this method to do something useful with the
080   * float we collect.
081   * <p>
082   * This method will be invoked by endElement with the fully parsed float.
083   *
084   * @param val  the fully parsed float
085   * @throws SAXException if for any reason the float is not palatable
086   */
087  protected abstract void setFloatValue(float val) throws SAXException;
088}