TemplateHandler.java :  » XML » X2JB » com » x2jb » bind » handler » Java Open Source

Java Open Source » XML » X2JB 
X2JB » com » x2jb » bind » handler » TemplateHandler.java
/*
 * XML 2 Java Binding (X2JB) - the excellent Java tool.
 * Copyright 2007, by Richard Opalka.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not see the FSF site:
 * http://www.fsf.org/ and search for the LGPL License document there.
 */
package com.x2jb.bind.handler;

import org.w3c.dom.Attr;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.w3c.dom.Element;
import org.x2jb.bind.handler.AttributeHandler;
import org.x2jb.bind.handler.ElementHandler;
import org.x2jb.bind.BindingException;

/**
 * Template handler extended by other handlers in this package
 *
 * @author <a href="mailto:richard_opalka@yahoo.com">Richard Opalka</a>
 * @version 1.0
 */
abstract class TemplateHandler implements ElementHandler, AttributeHandler {
    
    public Object bind( Attr a, Class clazz ) throws BindingException {
        String value = a.getValue();
        try {
            return create( value );
        } catch ( NumberFormatException nfe ) {
            throw new BindingException( "Incorrect value '" + value + "'", nfe );
        }
    }

    public Object bind( Element e, Class clazz ) throws BindingException {
        Node childNode = e.getFirstChild();
        if ( ( childNode == null ) || ( ! ( childNode instanceof Text ) ) ) {
            throw new BindingException( "Text node expected" );
        } else {
            String value = ( ( Text ) childNode ).getData();
            try {
                return create( value );
            } catch ( NumberFormatException nfe ) {
                throw new BindingException( "Incorrect value '" + value + "'", nfe );
            }
        }
    }

    public Object getDefault( Class clazz ) throws BindingException {
        return null;
    }

    protected abstract Object create( String value ) throws BindingException;

}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.