/* Copyright (c) 2005 Ricebridge. All Rights Reserved.
 *
 * This file is available under the terms and conditions of the
 * Ricebridge "Open Source API" policy; Ricebridge grants use of this
 * copyrighted work under the terms of a BSD-style license only. See
 * http://www.opensource.org/licenses/bsd-license.php for more
 * information.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 
 *  - Redistributions of source code must retain the above copyright
 *  notice, this list of conditions and the following disclaimer.
 *
 *  - Redistributions in binary form must reproduce the above
 *  copyright notice, this list of conditions and the following
 *  disclaimer in the documentation and/or other materials provided
 *  with the distribution.
 *
 *  - Neither the name of the Ricebridge nor the names of its
 *  contributors may be used to endorse or promote products derived
 *  from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.  
 */

package com.ricebridge.xmlman;

import com.ricebridge.data.BeanSpec;
import com.ricebridge.data.DataException;

import org.jostraca.util.Internal;

import java.util.*;


/** Implementation of {@link RecordListener} that stores data records as 
 *  a <code>List</code> of <a href="http://java.sun.com/products/javabeans">Java Beans</a>.
 *    <p>This class is used to implement the {@link XmlManager#loadBeans(File,RecordSpec,BeanSpec) loadBeans(*,RecordSpec,BeanSpec)} 
 *  methods in {@link XmlManager}.
 *  Data records are stored in new instances of Java Bean objects by calling the property <i>set</i> methods
 *  of the objects in accordance with the Java Beans specification. Ordinary, boolean and indexed properties are supported.
 *  See the {@link BeanSpec} documentation for more information.</p>
 *    <p><code>BeanRecordListener</code> is designed to be subclassed. You can change the default implementation by calling the 
 *  {@link com.ricebridge.xmlman.in.XmlManagerStoreBase#setBeanRecordListenerClass setBeanRecordListenerClass} method of 
 *  {@link com.ricebridge.xmlman.in.XmlManagerStore}, and providing a subclass of <code>BeanRecordListener</code>. 
 *  <code>XmlManagerStore</code> can be accessed using {@link XmlManager#getXmlManagerStore}.</p>
 *    <p>The <b><a href="BeanRecordListener.java.html">Source Code</a></b> of this Java class 
 *    is available under a <a href="http://www.opensource.org/licenses/bsd-license.php">BSD-style license</a>.</p>
 */
public class BeanRecordListener extends RecordListenerSupport {

  /** Specify that empty data fields have the default value for their data type
   *  (name for {@link XmlSpec#setProperty XmlSpec.setProperty}: <code>Bean.useDefault</code>). */
  public static final String PROP_Bean_useDefault = "Bean.useDefault";


  // protected instance

  /** List of beans loaded. */
  protected ArrayList         iBeans            = new ArrayList();
  
  /** {@link BeanSpec} specification object defining the properties of the beans to load. */
  protected BeanSpec          iBeanSpec         = null;

  /** If a data field is empty, use the default value of the property for that field data type. */
  protected boolean           iUseDefault       = false;



  // constructors

  /** Constructor with no parameters required for creating new objects in 
   *  {@link com.ricebridge.xmlman.in.XmlManagerStoreBase#newBeanRecordListener XmlManagerStore.newBeanRecordListener}.
   */
  public BeanRecordListener() {
    // do nothing
  }


  // public methods

  /** Set the {@link BeanSpec} object that defines the beans to load. 
   *    <p>The <code>BeanSpec</code> object contains the definitions of the 
   *  bean properties and performs the conversion from <code>String</code> values to internal Java data types.</p>
   *  @param pBeanSpec {@link BeanSpec} definition of beans to load
   */
  public void setBeanSpec( BeanSpec pBeanSpec ) {
    iBeanSpec = (BeanSpec) Internal.null_arg( pBeanSpec );
  }
  

  /** Get the data records as <code>List</code> of <a href="http://java.sun.com/products/javabeans">Java Bean</a> objects.
   *  @return <code>List</code> of beans
   */
  public List getBeans() {
    return iBeans;
  }


  /** Return a textual description suitable for debugging. */
  public String toString() {
    return "BeanRecordListener[size="+iBeans.size()+"]";
  }



  // protected methods

  /** Handle property settings for loading <a href="http://java.sun.com/products/javabeans">Java Bean</a>. 
   *    <p>You can change these using {@link XmlSpec}.</p>
   *  @see RecordListener#setXmlSpec
   *  @see #PROP_Bean_useDefault
   */
  protected void setXmlSpecImpl( XmlSpec pXmlSpec ) {
    iUseDefault = pXmlSpec.getBooleanProperty( PROP_Bean_useDefault );
  }


  /** Start the load process. 
   *   <p>Performs some sanity checks on the loading setup.</p>
   */
  protected void startProcessImpl() {
    Internal.null_state( iFieldNames );
    Internal.null_array( iFieldNames );
    Internal.null_state( iBeanSpec );
  }

  
  /** Store the data record <code>String[]</code>. 
   *  @see RecordListener#handleRecord
   */
  protected BadRecord handleRecordImpl( String[] pRecord, long pRecordNumber ) throws Exception {
    Object    bean = makeBean( pRecord );
    BadRecord br   = handleBean( bean );
    return br;
  }


  /** Store a bean object in the list of beans.
   *  @param pBean bean object
   */
  protected BadRecord handleBean( Object pBean ) {
    iBeans.add( pBean );
    return null;
  }


  /** Create a new instance of the bean specified by the {@link BeanSpec}
   *  and sets the bean properties data from the record <code>String[]</code> array.
   *  @param pRecord record data
   */
  protected Object makeBean( String[] pRecord ) {
    Object bean = null;
    Class  bc   = null;
      
    try {
      bc   = iBeanSpec.getBeanClass();
      bean = bc.newInstance();
    }
    catch( XmlManagerException xme ) { throw xme; }
    catch( Exception e ) {
      throw new XmlManagerException( XmlManagerException.CODE_newbean, 
                                     new String[] {"bean-class", null==bc?"[unknown]":bc.getName()}, e );
    }

    for( int fI = 0; fI < iFieldNames.length; fI++ ) {
      try {
        iBeanSpec.setStringValue( bean, iFieldNames[fI], pRecord[fI], iUseDefault );
      }
      catch( XmlManagerException xme ) { throw xme; }
      catch( DataException de ) {
        throw new XmlManagerException( XmlManagerException.CODE_setbeanfield_msg,
                                       new String[] {"bean-class", null==bc?"[unknown]":bc.getName(),
                                                     "field-name",iFieldNames[fI], "field-string", pRecord[fI], 
                                                     "datamsg", de.getUserMessage()} );
      }
      catch( Exception e ) {
        throw new XmlManagerException( XmlManagerException.CODE_setbeanfield, 
                                       new String[] {"bean-class", null==bc?"[unknown]":bc.getName(),
                                                     "field-name",iFieldNames[fI], "field-string", pRecord[fI] }, e );
      }
    }

    return bean;
  }
   
}
Syntax Highlighting created using the com.Ostermiller.Syntax package.
Thursday, February 23 2006 at 16:47