content: /**
   **************************************************************************************
   *** MatcherValueDAO.java                                                           ***
   *** Generator: net.anotheria.asg.generator.model.db.PersistenceServiceDAOGenerator ***
   *** generated by AnoSiteGenerator (ASG), Version: 1.3.3                            ***
   *** Copyright (C) 2005 - 2010 Anotheria.net, www.anotheria.net                     ***
   *** All Rights Reserved.                                                           ***
   **************************************************************************************
   *** Don't edit this code, if you aren't sure                                       ***
   *** that you do exactly know what you are doing!                                   ***
   *** It's better to invest time in the generator, as into the generated code.       ***
   **************************************************************************************
   */
  
  package net.anotheria.moskito.sql.callingAspect;
  
  import net.anotheria.db.config.JDBCConfig;
  import net.anotheria.db.config.JDBCConfigFactory;
  import net.anotheria.db.dao.DAO;
  import net.anotheria.db.dao.DAOException;
  import net.anotheria.db.dao.DAOSQLException;
  import net.anotheria.db.dao.RowMapper;
  import net.anotheria.util.slicer.Segment;
  import org.slf4j.Logger;
  import org.slf4j.LoggerFactory;
  
  import java.sql.Connection;
  import java.sql.PreparedStatement;
  import java.sql.ResultSet;
  import java.sql.SQLException;
  import java.sql.Statement;
  import java.util.ArrayList;
  import java.util.List;
  import java.util.concurrent.atomic.AtomicLong;
  
  public class MatcherValueDAO implements DAO{
  
  	private static Logger log = LoggerFactory.getLogger(MatcherValueDAO.class);
  	public static final String TABNAME = "matchervalue";
  
  	public static final String ATT_NAME_ID = "id";
  	public static final String ATT_NAME_TYPE 	 = "type";
  	public static final String ATT_NAME_VALUE 	 = "value";
  	public static final String ATT_NAME_MATCHERID 	 = "matcherid";
  
  	public static final String  SQL_CREATE_1 	= "INSERT INTO ";
  	public static final String  SQL_CREATE_2 	= " ("+ATT_NAME_ID+", "+ATT_NAME_TYPE+", "+ATT_NAME_VALUE+", "+ATT_NAME_MATCHERID+", "+ATT_NAME_DAO_CREATED+") VALUES (?,?,?,?,?)";
  	public static final String  SQL_UPDATE_1 	= "UPDATE ";
  	public static final String  SQL_UPDATE_2 	= " SET " + ATT_NAME_TYPE + " = ?, " + ATT_NAME_VALUE + " = ?, " + ATT_NAME_MATCHERID + " = ?, " + ATT_NAME_DAO_UPDATED + " = ?" + " WHERE " + ATT_NAME_ID + " = ?";
  	public static final String  SQL_DELETE_1 	= "DELETE FROM ";
  	public static final String  SQL_DELETE_2 	= " WHERE " + TABNAME +"." + ATT_NAME_ID + " = ?";
  	public static final String  SQL_READ_ONE_1 	= "SELECT "+ATT_NAME_ID+", "+ATT_NAME_TYPE+", "+ATT_NAME_VALUE+", "+ATT_NAME_MATCHERID+", "+ATT_NAME_DAO_CREATED+", "+ATT_NAME_DAO_UPDATED+" FROM ";
  	public static final String  SQL_READ_ONE_2 	= " WHERE " + TABNAME +"." + ATT_NAME_ID + " = ?";
  	public static final String  SQL_READ_ALL_1 	= "SELECT "+ATT_NAME_ID+", "+ATT_NAME_TYPE+", "+ATT_NAME_VALUE+", "+ATT_NAME_MATCHERID+", "+ATT_NAME_DAO_CREATED+", "+ATT_NAME_DAO_UPDATED+" FROM ";
  	public static final String  SQL_READ_ALL_2 	= " ORDER BY id";
  	public static final String  SQL_READ_ALL_BY_PROPERTY_1 	= "SELECT "+ATT_NAME_ID+", "+ATT_NAME_TYPE+", "+ATT_NAME_VALUE+", "+ATT_NAME_MATCHERID+", "+ATT_NAME_DAO_CREATED+", "+ATT_NAME_DAO_UPDATED+" FROM ";
  	public static final String  SQL_READ_ALL_BY_PROPERTY_2 	= " WHERE ";
  	public static final String  SQL_COUNT_1 	= "SELECT COUNT(id) FROM ";
  	public static final String  SQL_LIMIT_1 	= " LIMIT ?";
  	public static final String  SQL_OFFSET_1 	= " OFFSET ?";
  
  	private RowMapper<MatcherValue> rowMapper = new MatcherValueRowMapper();
  
  	private AtomicLong lastId = new AtomicLong();
  	private JDBCConfig dbConfig = JDBCConfigFactory.getJDBCConfig();
  
  	private AtomicLong getLastId(Connection con) throws DAOException {
  		return lastId;
  	}
  
  	private void adjustLastId(Connection con, long lastIdValue) throws DAOException {
  		if (lastId.get()<lastIdValue)
  			lastId.set(lastIdValue);
  	}
  
  	private String createSQL(String sql1, String sql2){
  		StringBuilder sql = new StringBuilder();
  		sql.append(sql1).append(TABNAME).append(sql2);
  		return sql.toString();
  	}
  
  	/**
  	 * Returns all MatcherValues objects stored.
  	 */
  	public List<MatcherValue> getMatcherValues(Connection con) throws DAOException {
  		PreparedStatement ps = null;
  		ResultSet result = null;
  		try {
  			con.setAutoCommit(true);
  			ps = con.prepareStatement(createSQL(SQL_READ_ALL_1, SQL_READ_ALL_2));
  			result = ps.executeQuery();
  			ArrayList<MatcherValue> ret = new ArrayList<MatcherValue>();
  			while(result.next())
  				ret.add(rowMapper.map(result));
  			return  ret;
  		} catch (SQLException e) {
  			log.error("getMatcherValues("+con+")", e);
  			throw new DAOSQLException(e);
  		} finally {
  			net.anotheria.db.util.JDBCUtil.release(result);
  			net.anotheria.db.util.JDBCUtil.release(ps);
  		}
  	}
  
  	/**
  	 * Deletes a MatcherValue object by id.
  	 */
  	public void deleteMatcherValue(Connection con, String id) throws DAOException {
  		PreparedStatement ps = null;
  		try {
  			con.setAutoCommit(true);
  			ps = con.prepareStatement(createSQL(SQL_DELETE_1, SQL_DELETE_2));
  			ps.setLong(1, Long.parseLong(id));
  			int rows = ps.executeUpdate();
  			if (rows!=1 && rows!=0){
  				log.warn("Deleted more than one row of MatcherValue: "+id);
  			}
  		} catch (SQLException e) {
  			log.error("deleteMatcherValue("+con+", "+id+")", e);
  			throw new DAOSQLException(e);
  		} finally {
  			net.anotheria.db.util.JDBCUtil.release(ps);
  		}
  	}
  
  	/**
  	 * Deletes multiple MatcherValue objects.
  	 */
  	public void deleteMatcherValues(Connection con, List<MatcherValue> list) throws DAOException {
  		PreparedStatement ps = null;
  		try{
  			con.setAutoCommit(false);
  			ps = con.prepareStatement(createSQL(SQL_DELETE_1, SQL_DELETE_2));
  			for (MatcherValue matchervalue : list){
  				ps.setLong(1, Long.parseLong(matchervalue.getId()));
  				int rows = ps.executeUpdate();
  				if (rows!=1 && rows!=0){
  					log.warn("Deleted more than one row of MatcherValue: "+matchervalue.getId());
  				}
  			}
  			con.commit();
  		} catch (SQLException e) {
  			log.error("deleteMatcherValues("+con+", "+list+")", e);
  			throw new DAOSQLException(e);
  		} finally {
  			net.anotheria.db.util.JDBCUtil.release(ps);
  		}
  	}
  
  	/**
  	 * Returns the MatcherValue object with the specified id.
  	 */
  	public MatcherValue getMatcherValue(Connection con, String id) throws DAOException {
  		if(con == null)
  			throw new IllegalArgumentException("Null arg: con");
  		if(id == null)
  			throw new IllegalArgumentException("Null arg: id");
  		PreparedStatement ps = null;
  		ResultSet result = null;
  		try {
  			con.setAutoCommit(true);
  			ps = con.prepareStatement(createSQL(SQL_READ_ONE_1, SQL_READ_ONE_2));
  			ps.setLong(1, Long.parseLong(id));
  			result = ps.executeQuery();
  			if (!result.next())
  				throw new RuntimeException(id);
  			return rowMapper.map(result);
  		} catch (SQLException e) {
  			log.error("getMatcherValue("+con+", "+id+")", e);
  			throw new DAOSQLException(e);
  		} finally {
  			net.anotheria.db.util.JDBCUtil.release(result);
  			net.anotheria.db.util.JDBCUtil.release(ps);
  		}
  	}
  
  	/**
  	 * Imports a new MatcherValue object.
  	 * Returns the imported version.
  	 */
  	public MatcherValue importMatcherValue(Connection con, MatcherValue matchervalue) throws DAOException {
  		PreparedStatement ps = null;
  		try {
  			con.setAutoCommit(true);
  			ps = con.prepareStatement(createSQL(SQL_CREATE_1, SQL_CREATE_2));
  			ps.setLong(1, Long.parseLong(matchervalue.getId()));
  			ps.setInt(2, matchervalue.getType());
  			ps.setString(3, matchervalue.getValue());
  			ps.setString(4, matchervalue.getMatcherId());
  			// set create timestamp
  			ps.setLong(5, System.currentTimeMillis());
  			int rows = ps.executeUpdate();
  			if (rows!=1)
  				throw new DAOException("Create failed, updated rows: "+rows);
  			MatcherValueVO newMatchervalue = new MatcherValueVO(matchervalue.getId());
  			newMatchervalue.copyAttributesFrom(matchervalue);
  			adjustLastId(con, Long.parseLong(matchervalue.getId()));
  			return newMatchervalue;
  		} catch (SQLException e) {
  			log.error("importMatcherValue("+con+", "+matchervalue+")", e);
  			throw new DAOSQLException(e);
  		} finally {
  			net.anotheria.db.util.JDBCUtil.release(ps);
  		}
  	}
  
  	/**
  	 * Imports multiple new MatcherValue objects.
  	 * Returns the imported versions.
  	 */
  	public List<MatcherValue> importMatcherValues(Connection con,List<MatcherValue> list) throws DAOException {
  		PreparedStatement ps = null;
  		try{
  			con.setAutoCommit(false);
  			ps = con.prepareStatement(createSQL(SQL_CREATE_1, SQL_CREATE_2));
  			List<MatcherValue> ret = new ArrayList<MatcherValue>();
  			for (MatcherValue matchervalue : list){
  				ps.setLong(1, Long.parseLong(matchervalue.getId()));
  				ps.setInt(2, matchervalue.getType());
  				ps.setString(3, matchervalue.getValue());
  				ps.setString(4, matchervalue.getMatcherId());
  				// set create timestamp
  				ps.setLong(5, System.currentTimeMillis());
  				int rows = ps.executeUpdate();
  				if (rows!=1)
  					throw new DAOException("Create failed, updated rows: "+rows);
  				MatcherValueVO newMatchervalue = new MatcherValueVO(matchervalue.getId());
  				newMatchervalue.copyAttributesFrom(matchervalue);
  				adjustLastId(con, Long.parseLong(matchervalue.getId()));
  				ret.add(newMatchervalue);
  			}
  			con.commit();
  			return ret;
  		} catch (SQLException e) {
  			log.error("import MatcherValues("+con+", "+list+")", e);
  			throw new DAOSQLException(e);
  		} finally {
  			net.anotheria.db.util.JDBCUtil.release(ps);
  		}
  	}
  
  	/**
  	 * Creates a new MatcherValue object.
  	 * Returns the created version.
  	 */
  	public MatcherValue createMatcherValue(Connection con, MatcherValue matchervalue) throws DAOException {
  		java.sql.SQLException throwable = null;
  		for (int recoveryAttempt = 1; recoveryAttempt <= dbConfig.getIdRecoveryAttempts(); recoveryAttempt++) {
  			PreparedStatement ps = null;
  			try {
  				con.setAutoCommit(false);
  				ps = con.prepareStatement(createSQL(SQL_CREATE_1, SQL_CREATE_2));
  				long nextId = getLastId(con).incrementAndGet();
  				ps.setLong(1, nextId);
  				ps.setInt(2, matchervalue.getType());
  				ps.setString(3, matchervalue.getValue());
  				ps.setString(4, matchervalue.getMatcherId());
  				// set create timestamp
  				ps.setLong(5, System.currentTimeMillis());
  				int rows = ps.executeUpdate();
  				if (rows!=1)
  					throw new DAOException("Create failed, updated rows: "+rows);
  				MatcherValueVO newMatchervalue = new MatcherValueVO(String.valueOf(nextId));
  				newMatchervalue.copyAttributesFrom(matchervalue);
  				con.commit();
  				return newMatchervalue;
  			} catch (SQLException e) {
  				getLastId(con).set(getMaxId(con,TABNAME));
  				log.warn("Failed attempt" +recoveryAttempt+ " from " +dbConfig.getIdRecoveryAttempts()+ " to create new entry in "+TABNAME+" table", e);
  				throwable = e;
  				continue;
  			} finally {
  				net.anotheria.db.util.JDBCUtil.release(ps);
  			}
  		}
  		log.error("All "+ dbConfig.getIdRecoveryAttempts()+" attempt of id rereading - Failed. "+"createMatcherValue("+con+", "+matchervalue+")", throwable);
  		throw new DAOSQLException(throwable);
  	}
  
  	/**
  	 * Creates multiple new MatcherValue objects.
  	 * Returns the created versions.
  	 */
  	public List<MatcherValue> createMatcherValues(Connection con, List<MatcherValue> list) throws DAOException {
  		java.sql.SQLException throwable = null;
  		for (int recoveryAttempt = 1; recoveryAttempt <= dbConfig.getIdRecoveryAttempts(); recoveryAttempt++) {
  			PreparedStatement ps = null;
  			try{
  				con.setAutoCommit(false);
  				ps = con.prepareStatement(createSQL(SQL_CREATE_1, SQL_CREATE_2));
  				List<MatcherValue> ret = new ArrayList<MatcherValue>();
  				for (MatcherValue matchervalue : list){
  					long nextId = getLastId(con).incrementAndGet();
  					ps.setLong(1, nextId);
  					ps.setInt(2, matchervalue.getType());
  					ps.setString(3, matchervalue.getValue());
  					ps.setString(4, matchervalue.getMatcherId());
  					// set create timestamp
  					ps.setLong(5, System.currentTimeMillis());
  					int rows = ps.executeUpdate();
  					if (rows!=1)
  						throw new DAOException("Create failed, updated rows: "+rows);
  					MatcherValueVO newMatchervalue = new MatcherValueVO(String.valueOf(nextId));
  					newMatchervalue.copyAttributesFrom(matchervalue);
  					ret.add(newMatchervalue);
  				}
  				con.commit();
  				return ret;
  			} catch (SQLException e) {
  				getLastId(con).set(getMaxId(con,TABNAME));
  				log.warn("Failed attempt" +recoveryAttempt+ " from " +dbConfig.getIdRecoveryAttempts()+ " to create new entries (list) in "+TABNAME+" table", e);
  				throwable = e;
  				continue;
  			} finally {
  				net.anotheria.db.util.JDBCUtil.release(ps);
  			}
  		}
  		log.error("All "+ dbConfig.getIdRecoveryAttempts()+" attempt of id rereading - Failed. "+"createMatcherValues("+con+", "+list+")", throwable);
  		throw new DAOSQLException(throwable);
  	}
  
  	/**
  	 * Updates a MatcherValue object.
  	 * Returns the updated version.
  	 */
  	public MatcherValue updateMatcherValue(Connection con, MatcherValue matchervalue) throws DAOException {
  		PreparedStatement ps = null;
  		try {
  			con.setAutoCommit(true);
  			ps = con.prepareStatement(createSQL(SQL_UPDATE_1, SQL_UPDATE_2));
  			ps.setInt(1, matchervalue.getType());
  			ps.setString(2, matchervalue.getValue());
  			ps.setString(3, matchervalue.getMatcherId());
  			// set update timestamp
  			ps.setLong(4, System.currentTimeMillis());
  			// set id for the where clause
  			ps.setLong(5, Long.parseLong(matchervalue.getId()));
  			int rows = ps.executeUpdate();
  			if (rows!=1)
  				throw new DAOException("Update failed, updated rows: "+rows);
  			return matchervalue;
  		} catch (SQLException e) {
  			log.error("updateMatcherValue("+con+", "+matchervalue+")", e);
  			throw new DAOSQLException(e);
  		} finally {
  			net.anotheria.db.util.JDBCUtil.release(ps);
  		}
  	}
  
  	/**
  	 * Updates multiple new MatcherValue objects.
  	 * Returns the updated versions.
  	 */
  	public List<MatcherValue> updateMatcherValues(Connection con, List<MatcherValue> list) throws DAOException {
  		PreparedStatement ps = null;
  		try{
  			con.setAutoCommit(false);
  			ps = con.prepareStatement(createSQL(SQL_UPDATE_1, SQL_UPDATE_2));
  			List<MatcherValue> ret = new ArrayList<MatcherValue>();
  			for (MatcherValue matchervalue : list){
  				ps.setInt(1, matchervalue.getType());
  				ps.setString(2, matchervalue.getValue());
  				ps.setString(3, matchervalue.getMatcherId());
  				// set update timestamp
  				ps.setLong(4, System.currentTimeMillis());
  				// set id for the where clause
  				ps.setLong(5, Long.parseLong(matchervalue.getId()));
  				int rows = ps.executeUpdate();
  				if (rows!=1)
  					throw new DAOException("Update failed, updated rows: "+rows);
  			}
  			con.commit();
  			return list;
  		} catch (SQLException e) {
  			log.error("updateMatcherValues("+con+", "+list+")", e);
  			throw new DAOSQLException(e);
  		} finally {
  			net.anotheria.db.util.JDBCUtil.release(ps);
  		}
  	}
  
  
  
  	/**
  	 * Returns MatcherValues objects count.
  	 */
  	public int getMatcherValuesCount(Connection con) throws DAOException {
  		PreparedStatement ps = null;
  		ResultSet result = null;
  		try {
  			ps = con.prepareStatement(SQL_COUNT_1 + TABNAME);
  			result = ps.executeQuery();
  			int pCount = 0;
  			if (result.next())
  				pCount = result.getInt(1);
  			return pCount;
  		} catch (SQLException e) {
  			log.error("getMatcherValuesCount(" + con + ")", e);
  			throw new DAOSQLException(e);
  		} finally {
  			net.anotheria.db.util.JDBCUtil.release(result);
  			net.anotheria.db.util.JDBCUtil.release(ps);
  		}
  	}
  
  	/**
  	 * Returns MatcherValues objects segment.
  	 */
  	public List<MatcherValue> getMatcherValues(Connection con, Segment aSegment) throws DAOException {
  		PreparedStatement ps = null;
  		ResultSet result = null;
  		try {
  			con.setAutoCommit(true);
  			ps = con.prepareStatement(createSQL(SQL_READ_ALL_1, SQL_READ_ALL_2) + SQL_LIMIT_1 + SQL_OFFSET_1);
  			int pLimit = aSegment.getElementsPerSlice();
  			int pOffset = aSegment.getSliceNumber() * aSegment.getElementsPerSlice() - aSegment.getElementsPerSlice();
  			ps.setInt(1, pLimit);
  			ps.setInt(2, pOffset);
  			result = ps.executeQuery();
  			ArrayList<MatcherValue> ret = new ArrayList<MatcherValue>();
  			while(result.next())
  				ret.add(rowMapper.map(result));
  			return  ret;
  		} catch (SQLException e) {
  			log.error("getMatcherValues(" + con + ","+ aSegment +")", e);
  			throw new DAOSQLException(e);
  		} finally {
  			net.anotheria.db.util.JDBCUtil.release(result);
  			net.anotheria.db.util.JDBCUtil.release(ps);
  		}
  	}
  
  
  
  
  	/* ---------- SQL --------- 
  	CREATE TABLE matchervalue(
  	id int8 PRIMARY KEY,
  	type int,
  	value varchar,
  	matcherid varchar,
  	dao_created int8,
  	dao_updated int8
  	)
  	   ---------- SQL --------- */
  	public void createStructure(Connection connection)  throws DAOException {
  		// not implemented
  	}
  
  	/* ---------- SQL --------- 
  	DROP TABLE matchervalue
  	   ---------- SQL --------- */
  	public void deleteStructure(Connection connection)  throws DAOException {
  		// not implemented
  	}
  
  	private long getMaxId(Connection con, String tableName)  throws DAOException {
  		Statement st = null;
  		ResultSet result = null;
  		try {
  			con.setAutoCommit(true);
  			st = con.createStatement();
  			st.execute("SELECT MAX("+ATT_NAME_ID+") FROM "+tableName);
  			result = st.getResultSet();
  			long maxId = 0;
  			if (result.next())
  				maxId = result.getLong(1);
  			log.info("maxId in table "+tableName+" is "+maxId);
  			return maxId;
  		} catch (SQLException e) {
  			log.error("getMaxId("+con+", "+tableName+")", e);
  			throw new DAOSQLException(e);
  		} finally {
  			net.anotheria.db.util.JDBCUtil.release(result);
  			net.anotheria.db.util.JDBCUtil.release(st);
  		}
  	}
  
  	public void init(Connection con)  throws DAOException {
  		log.debug("Called: init("+con+")");
  		long maxId = getMaxId(con, TABNAME);
  		maxId = maxId >= dbConfig.getStartId() ? maxId : dbConfig.getStartId();
  		lastId = new AtomicLong(maxId);
  	}
  }
  