/* Copyright (c) 2006 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.csvman;

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

import org.jostraca.util.Internal;

import java.util.*;


/** Implementation of {@link LineListener} 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 CsvManager#loadBeans(Object, LineSpec, BeanSpec) loadBeans(Object,LineSpec,BeanSpec)} 
 *  method in {@link CsvManager}.</p>
 *    <p>Data records are stored in new instances of <i>Java Bean</i> objects by calling the 
 *  <i>set</i> property methods of the objects in accordance with the <i>Java Beans</i> specification. 
 *  Ordinary, boolean and indexed properties are supported. See the {@link BeanSpec} documentation 
 *  for more information.</p>
 *    <p><code>BeanLineListener</code> is designed to be subclassed. You can change
 *  the default implementation by calling the 
 *  {@link com.ricebridge.csvman.CsvManagerStore#setBeanLineListenerClass CsvManagerStore.setBeanLineListenerClass}
 *  method, and providing a subclass of 
 *  <code>BeanLineListener</code>. {@link CsvManagerStore} can be accessed 
 *  using {@link CsvManager#getCsvManagerStore}.</p>
 *    <p>The <b><a href="BeanLineListener.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>
 *
 *  @see LineListener
 *  @see CustomLineListener
 *  @see ResultSetLineListener 
 *  @see AsListsLineListener 
 *  @see TableModelLineListener 
 *  @see ResultSetLineListener 
 */
public class BeanLineListener extends CustomLineListener {

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

  /** Default value of <code>Bean.useDefault</code> (<code>false</code>). */
  public static final boolean DEFAULT_Bean_useDefault = false;


  /** Specify that the first line of the CSV file contains the <i>Java Bean</i> field names.
   *    <p>This is only used when no {@link LineSpec} has been provided. If a <code>LineSpec</code> has been
   *  provided, this setting is ignored and the first line is assumed to be normal data.</p>
   *  (name for {@link CsvSpec#setProperty CsvSpec.setProperty}: <code>Bean.firstLineFieldsAsNeeded</code>). 
   */
  public static final String PROP_Bean_firstLineFieldsAsNeeded = "Bean.firstLineFieldsAsNeeded";

  /** Default value of <code>Bean.firstLineFieldsAsNeeded</code>). */
  public static final boolean DEFAULT_Bean_firstLineFieldsAsNeeded = true;



  // 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 = DEFAULT_Bean_useDefault;

  /** Specify that the first line of the CSV file contains the Java Bean field names. */
  protected boolean iFirstLineFieldsAsNeeded = DEFAULT_Bean_firstLineFieldsAsNeeded;

  /** Description of the data fields. */
  protected LineSpec iLineSpec = null;

  /** The names of the data fields, corresponding to the names of the <i>Java Bean</i> property methods. */
  protected String[] iFieldNames = null;
  
  

  // 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 "BeanLineListener[size="+iBeans.size()+"]";
  }



  // protected methods

  /** Handle property settings for loading <a href="http://java.sun.com/products/javabeans">Java Beans</a>. 
   *    <p>You can change these using {@link CsvSpec}.</p>
   *    <p>The properties you can use here are: {@link #PROP_Bean_useDefault} and 
   *  {@link #PROP_Bean_firstLineFieldsAsNeeded}.</p>
   *  @see LineListener#setCsvSpec
   *  @see #PROP_Bean_useDefault
   */
  protected void setCsvSpecImpl( CsvSpec pCsvSpec ) throws Exception {
    iUseDefault              = pCsvSpec.getBooleanProperty( PROP_Bean_useDefault );
    iFirstLineFieldsAsNeeded = pCsvSpec.getBooleanProperty( PROP_Bean_firstLineFieldsAsNeeded );
  }


  /** Use the {@link LineSpec} to map data fields to <i>Java Bean</i> methods.
   *  @see LineListener#setLineSpec
   */
  protected void setLineSpecImpl( LineSpec pLineSpec ) throws Exception {
    iFieldNames = pLineSpec.getFieldNames();
  }


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

  
  /** Convert the data line <code>String[]</code> in a <i>Java Bean</i> instance and store it in a list. 
   *  @see LineListener#handleLine
   */
  public BadLine handleLineImpl( String[] pLine, int pNumFields, long pLineNumber, String pOriginalLine ) throws Exception {
    BadLine badline = null;

    // first line is considered to be field names if none specified
    if( null == iFieldNames || 0 == iFieldNames.length ) {
      if( iFirstLineFieldsAsNeeded ) {
        iFieldNames = makeFieldNames( pLine, pNumFields );
      }
      else {
        throw new CsvManagerException( CsvManagerException.CODE_nofieldnames,
                                       new String[] {"line-listener-class", this.getClass().getName()} );
      }
    }
    else {
      Object bean = makeBean( pLine );
      badline = handleBean( bean );
    }

    return badline;
  }


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


  /** Create a new instance of the bean specified by the {@link BeanSpec}
   *  and set the bean properties data from the data line <code>String[]</code> array.
   *  @param pLine record data
   */
  protected Object makeBean( String[] pLine ) {
    Class  bc   = iBeanSpec.getBeanClass();
    Object bean = newBean( bc, pLine );

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

    return bean;
  }


  /** Create a new instance of the <i>Java Bean</i> object.
   *  @param pBeanClass class of bean to create
   *  @param pLine      current data line
   */
  protected Object newBean( Class pBeanClass, String[] pLine ) {
    Object bean = null;
      
    try {
      bean = pBeanClass.newInstance();
    }
    catch( CsvManagerException xme ) { throw xme; }
    catch( Exception e ) {
      throw new CsvManagerException( CsvManagerException.CODE_newbean, 
                                     new String[] {"bean-class", null==pBeanClass?"[unknown]":pBeanClass.getName()}, e );
    }

    return bean;
  }


  /** Interpret the first line of data as the property field names.
   *    <p>These names will be used to identify the get and set method names for each data field.
   *  The names will be capitalised if necessary.</p>
   * @param pLine      header line of data, containing field names
   * @param pNumFields number of actual fields, may be less than pLine.length
   * @return array of <i>Java Bean</i> field names
   */
  protected String[] makeFieldNames( String[] pLine, int pNumFields ) {
    String[] fieldnames = new String[pNumFields];
    for( int fI = 0; fI < pLine.length; fI++ ) {
      String fn = pLine[fI];
      if( 0 == fn.length() ) {
        throw new CsvManagerException( CsvManagerException.CODE_emptyfieldname,
                                       new String[] { "fieldnum", ""+(fI+1),
                                                      "line-listener-class", this.getClass().getName()} );
      }

      if( !Character.isUpperCase( fn.charAt(0) ) ) {
        fn = fn.substring(0,1).toUpperCase()+fn.substring(1);
      }
      fieldnames[fI] = fn;
    }
    return fieldnames;
  }
}
Syntax Highlighting created using the com.Ostermiller.Syntax package.
Wednesday, November 08 2006 at 19:54