/**
 * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
 * 
 * Please see distribution for license.
 */

package com.opengamma.integration.copier.sheet.reader;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.util.ArgumentChecker;

/**
 * A class to facilitate importing portfolio data from a JDBC query result
 */
public class JdbcSheetReader extends SheetReader {

  private DataSource _dataSource;
  private JdbcTemplate _jdbcTemplate;
  private ResultSet _resultSet;
  private String[] _row;
  private List<Map<String, String>> _results;
  private Iterator<Map<String, String>> _iterator;
  private static final Logger s_logger = LoggerFactory.getLogger(JdbcSheetReader.class);
  
  public JdbcSheetReader(DataSource dataSource, String query) {
    init(dataSource, query, null);
  }
  
  public JdbcSheetReader(DataSource dataSource, String query, PreparedStatementSetter preparedStatementSetter) {
    ArgumentChecker.notNull(preparedStatementSetter, "prepared statement setter");
    init(dataSource, query, preparedStatementSetter);
  }
  
  protected void init(DataSource dataSource, String query, PreparedStatementSetter preparedStatementSetter) {
    ArgumentChecker.notNull(dataSource, "dataSource");
    
    _jdbcTemplate = new JdbcTemplate(dataSource);
     
    ResultSetExtractor<List<Map<String, String>>> extractor = new ResultSetExtractor<List<Map<String, String>>>() {
      @Override
      public List<Map<String, String>> extractData(ResultSet rs) throws SQLException, DataAccessException {
        String[] columns = new String[rs.getMetaData().getColumnCount()];
        for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
          columns[i] = rs.getMetaData().getColumnName(i + 1);
        }
        setColumns(columns);
        List<Map<String, String>> entries = new ArrayList<Map<String, String>>();
        while (rs.next()) {
          s_logger.info("Read a row");
          String[] rawRow = new String[rs.getMetaData().getColumnCount()];
          for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
            rawRow[i] = rs.getString(i + 1);
          }
          Map<String, String> result = new HashMap<String, String>();
          // Map read-in row onto expected columns
          for (int i = 0; i < getColumns().length; i++) {
            if (i >= rawRow.length) {
              break;
            }
            if (rawRow[i] != null && rawRow[i].trim().length() > 0) {
              result.put(getColumns()[i], rawRow[i]);
            }
          }
          entries.add(result);
        }
        return entries;
      }
    };
    if (preparedStatementSetter != null) {
      _results = getJDBCTemplate().query(query, preparedStatementSetter, extractor);
    } else {
      _results = getJDBCTemplate().query(query, extractor);
    }
    _iterator = _results.iterator();
  }
  
  private JdbcTemplate getJDBCTemplate() {
    return _jdbcTemplate;
  }

  @Override
  public Map<String, String> loadNextRow() {
    if (_iterator.hasNext()) {
      s_logger.info("Returned a row");
      return _iterator.next();
    } else {
      return null;
    }
  }

  @Override
  public void close() {
  }
}

@@ -86,18 +86,17 @@
 anies%0A *
- 
 %0A
+
  * Pleas
@@ -1443,19 +1443,17 @@
 class);%0A
-  
 %0A
+
   public
@@ -1547,19 +1547,17 @@
 l);%0A  %7D%0A
-  
 %0A
+
   public
@@ -1665,91 +1665,8 @@
 ) %7B%0A
-    ArgumentChecker.notNull(preparedStatementSetter, %22prepared statement setter%22);%0A
     
@@ -1715,27 +1715,25 @@
 etter);%0A  %7D%0A
-  
 %0A
+
   protected 
@@ -1885,24 +1885,66 @@
 urce%22);%0A    
+ArgumentChecker.notEmpty(query, %22query%22);%0A
 %0A    _jdbcTe
@@ -1986,14 +1986,9 @@
 e);%0A
-     
 %0A
+
     
@@ -3551,18 +3551,16 @@
 ();%0A  %7D%0A
-  
 %0A  priva

Allow prepared statement setter argument to be null in JDBC sheet reader constructor