/* 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.lang.reflect.Method;

import java.util.*;


/** Simple implementation of {@link LineProvider} that provides data records for saving
 *  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#saveBeans(Object, LineSpec, BeanSpec, List) saveBeans(Object,LineSpec,BeanSpec,List)} 
 *  methods in {@link CsvManager}.
 *  Data records are created from Java Bean objects by calling the property <i>get</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>BeanLineProvider</code> is designed to be subclassed. You can change the default implementation by calling the 
 *  {@link com.ricebridge.csvman.in.CsvManagerStoreBase#setBeanLineProviderClass setBeanLineProviderClass} method of 
 *  {@link com.ricebridge.csvman.CsvManagerStore}, and providing a subclass of <code>BeanLineProvider</code>. 
 *  <code>CsvManagerStore</code> can be accessed using {@link CsvManager#getCsvManagerStore}.</p>
 *    <p>The <b><a href="BeanLineProvider.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 BeanLineProvider extends CustomLineProvider {

  /** Specify that invalid 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>). */
  public static final boolean DEFAULT_Bean_useDefault = false;


  /** Output headers as first data line
   *  (name for {@link CsvSpec#setProperty CsvSpec.setProperty}: <code>Bean.saveHeaders</code>). */
  public static final String PROP_Bean_saveHeaders = "Bean.saveHeaders";

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


  // protected instance

  /** <code>List</code> of Beans. */
  protected List iBeans = null;

  /** Index of current bean in <code>List</code>. */
  protected int iBeanIndex = 0;

  /** {@link BeanSpec} specification object defining the properties of the beans to save. */
  protected BeanSpec iBeanSpec = null;

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

  /** Output headers as first data line. */
  protected boolean iSaveHeaders = false;

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

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

  
  // constructors

  /** Create uninitialised for use with {@link #setBeans}. */
  public BeanLineProvider() {
    // init with setData
  }


  /** Create using a <code>List</code> of <a href="http://java.sun.com/products/javabeans">Java Beans</a> to save. */
  public BeanLineProvider( List pData ) {
    setBeans( iBeans );
  }



  // public methods

  /** Set the <a href="http://java.sun.com/products/javabeans">Java Beans</a> to save. */
  public void setBeans( List pBeans ) {
    iBeans = (List) Internal.null_list( pBeans );
  }

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



  // LineProviderSupport methods


  // only called if not null
  protected void setLineSpecImpl( LineSpec pLineSpec ) throws Exception {
    iFieldNames = pLineSpec.getFieldNames();
  }


  /** Handle property settings for saving <a href="http://java.sun.com/products/javabeans">Java Beans</a>. 
   *    <p>You can change these using {@link CsvSpec}.</p>
   *  @see LineListener#setCsvSpec
   *  @see #PROP_Bean_useDefault
   */
  protected void setCsvSpecImpl( CsvSpec pCsvSpec ) throws Exception {
    iUseDefault  = pCsvSpec.getBooleanProperty( PROP_Bean_useDefault );
    iSaveHeaders = pCsvSpec.getBooleanProperty( PROP_Bean_saveHeaders );
  }


  /** Start the load process.
   *   <p>Performs some sanity checks on the saving setup.</p>
   */
  protected void startProcessImpl() throws Exception {
    Internal.null_state( iBeanSpec );
    if( null == iFieldNames || 0 == iFieldNames.length ) {
      iFieldNames = iBeanSpec.getGetterNames();
    }
    iBeanIndex = 0;
  }


  /** Check if there are any beans left. */
  protected boolean hasNextLineImpl() throws Exception {
    return iBeanIndex < iBeans.size();
  }


  /** Return data fields of next bean as a <code>String[]</code> array. */
  protected String[] nextLineImpl() throws Exception {
    Object   bean   = iBeans.get( iBeanIndex );
    Class    bc     = bean.getClass();
    String[] record = new String[iFieldNames.length];
    for( int fI = 0; fI < iFieldNames.length; fI++ ) {
      try {
        record[fI] = iBeanSpec.getStringValue( bean, iFieldNames[fI], iUseDefault );
      }
      catch( CsvManagerException xme ) { throw xme; }
      catch( DataException de ) {
        throw new CsvManagerException( CsvManagerException.CODE_getbeanfield_msg, 
                                       new String[] {"bean-class", null==bc?"[unknown]":bc.getName(),
                                                     "field-name",iFieldNames[fI],
                                                     "datamsg", de.getUserMessage() } );
      }
      catch( Exception e ) {
        throw new CsvManagerException( CsvManagerException.CODE_getbeanfield, 
                                       new String[] {"bean-class", null==bc?"[unknown]":bc.getName(),
                                                     "field-name",iFieldNames[fI] }, e );
      }
    }

    iBeanIndex++;
    return record;
  }


}
Syntax Highlighting created using the com.Ostermiller.Syntax package.
Monday, October 30 2006 at 11:33