You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ibatis.apache.org by cb...@apache.org on 2008/08/08 01:21:58 UTC
svn commit: r683745 [2/22] - in /ibatis/trunk/java/ibatis-3: ./
ibatis-3-compat/ ibatis-3-compat/src/ ibatis-3-compat/src/main/
ibatis-3-compat/src/main/java/ ibatis-3-compat/src/main/java/com/
ibatis-3-compat/src/main/java/com/ibatis/ ibatis-3-compat/...
Added: ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/common/util/PaginatedArrayList.java
URL: http://svn.apache.org/viewvc/ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/common/util/PaginatedArrayList.java?rev=683745&view=auto
==============================================================================
--- ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/common/util/PaginatedArrayList.java (added)
+++ ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/common/util/PaginatedArrayList.java Thu Aug 7 16:21:46 2008
@@ -0,0 +1,246 @@
+package com.ibatis.common.util;
+
+import java.util.*;
+
+/**
+ * Implementation of PaginatedList backed by an ArrayList
+ */
+public class PaginatedArrayList implements PaginatedList {
+
+ private static final ArrayList EMPTY_LIST = new ArrayList(0);
+
+ private List list;
+ private List page;
+ private int pageSize;
+ private int index;
+
+ /**
+ * @param pageSize
+ */
+ public PaginatedArrayList(int pageSize) {
+ this.pageSize = pageSize;
+ this.index = 0;
+ this.list = new ArrayList();
+ repaginate();
+ }
+
+ /**
+ * Constructor to set the initial size and the page size
+ *
+ * @param initialCapacity - the initial size
+ * @param pageSize - the page size
+ */
+ public PaginatedArrayList(int initialCapacity, int pageSize) {
+ this.pageSize = pageSize;
+ this.index = 0;
+ this.list = new ArrayList(initialCapacity);
+ repaginate();
+ }
+
+ /**
+ * Constructor to create an instance using an existing collection
+ *
+ * @param c - the collection to build the instance with
+ * @param pageSize - the page size
+ */
+ public PaginatedArrayList(Collection c, int pageSize) {
+ this.pageSize = pageSize;
+ this.index = 0;
+ this.list = new ArrayList(c);
+ repaginate();
+ }
+
+ private void repaginate() {
+ if (list.isEmpty()) {
+ page = EMPTY_LIST;
+ } else {
+ int start = index * pageSize;
+ int end = start + pageSize - 1;
+ if (end >= list.size()) {
+ end = list.size() - 1;
+ }
+ if (start >= list.size()) {
+ index = 0;
+ repaginate();
+ } else if (start < 0) {
+ index = list.size() / pageSize;
+ if (list.size() % pageSize == 0) {
+ index--;
+ }
+ repaginate();
+ } else {
+ page = list.subList(start, end + 1);
+ }
+ }
+ }
+
+ /* List accessors (uses page) */
+
+ public int size() {
+ return page.size();
+ }
+
+ public boolean isEmpty() {
+ return page.isEmpty();
+ }
+
+ public boolean contains(Object o) {
+ return page.contains(o);
+ }
+
+ public Iterator iterator() {
+ return page.iterator();
+ }
+
+ public Object[] toArray() {
+ return page.toArray();
+ }
+
+ public Object[] toArray(Object a[]) {
+ return page.toArray(a);
+ }
+
+ public boolean containsAll(Collection c) {
+ return page.containsAll(c);
+ }
+
+ public Object get(int index) {
+ return page.get(index);
+ }
+
+ public int indexOf(Object o) {
+ return page.indexOf(o);
+ }
+
+ public int lastIndexOf(Object o) {
+ return page.lastIndexOf(o);
+ }
+
+ public ListIterator listIterator() {
+ return page.listIterator();
+ }
+
+ public ListIterator listIterator(int index) {
+ return page.listIterator(index);
+ }
+
+ public List subList(int fromIndex, int toIndex) {
+ return page.subList(fromIndex, toIndex);
+ }
+
+ /* List mutators (uses master list) */
+
+ public boolean add(Object o) {
+ boolean b = list.add(o);
+ repaginate();
+ return b;
+ }
+
+ public boolean remove(Object o) {
+ boolean b = list.remove(o);
+ repaginate();
+ return b;
+ }
+
+ public boolean addAll(Collection c) {
+ boolean b = list.addAll(c);
+ repaginate();
+ return b;
+ }
+
+ public boolean addAll(int index, Collection c) {
+ boolean b = list.addAll(index, c);
+ repaginate();
+ return b;
+ }
+
+ public boolean removeAll(Collection c) {
+ boolean b = list.removeAll(c);
+ repaginate();
+ return b;
+ }
+
+ public boolean retainAll(Collection c) {
+ boolean b = list.retainAll(c);
+ repaginate();
+ return b;
+ }
+
+ public void clear() {
+ list.clear();
+ repaginate();
+ }
+
+ public Object set(int index, Object element) {
+ Object o = list.set(index, element);
+ repaginate();
+ return o;
+ }
+
+ public void add(int index, Object element) {
+ list.add(index, element);
+ repaginate();
+ }
+
+ public Object remove(int index) {
+ Object o = list.remove(index);
+ repaginate();
+ return o;
+ }
+
+ /* Paginated List methods */
+
+ public int getPageSize() {
+ return pageSize;
+ }
+
+ public boolean isFirstPage() {
+ return index == 0;
+ }
+
+ public boolean isMiddlePage() {
+ return !(isFirstPage() || isLastPage());
+ }
+
+ public boolean isLastPage() {
+ return list.size() - ((index + 1) * pageSize) < 1;
+ }
+
+ public boolean isNextPageAvailable() {
+ return !isLastPage();
+ }
+
+ public boolean isPreviousPageAvailable() {
+ return !isFirstPage();
+ }
+
+ public boolean nextPage() {
+ if (isNextPageAvailable()) {
+ index++;
+ repaginate();
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public boolean previousPage() {
+ if (isPreviousPageAvailable()) {
+ index--;
+ repaginate();
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public void gotoPage(int pageNumber) {
+ index = pageNumber;
+ repaginate();
+ }
+
+ public int getPageIndex() {
+ return index;
+ }
+
+}
Added: ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/common/util/PaginatedList.java
URL: http://svn.apache.org/viewvc/ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/common/util/PaginatedList.java?rev=683745&view=auto
==============================================================================
--- ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/common/util/PaginatedList.java (added)
+++ ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/common/util/PaginatedList.java Thu Aug 7 16:21:46 2008
@@ -0,0 +1,91 @@
+package com.ibatis.common.util;
+
+import java.util.List;
+
+/**
+ * Interface for lists that support paging
+ */
+public interface PaginatedList extends List {
+
+ /**
+ * Returns the maximum number of items per page
+ *
+ * @return The maximum number of items per page.
+ */
+ public int getPageSize();
+
+ /**
+ * Is the current page the first page?
+ *
+ * @return True if the current page is the first page or if only
+ * a single page exists.
+ */
+ public boolean isFirstPage();
+
+ /**
+ * Is the current page a middle page (ie not first or last)?
+ *
+ * @return True if the current page is not the first or last page,
+ * and more than one page exists (always returns false if only a
+ * single page exists).
+ */
+ public boolean isMiddlePage();
+
+ /**
+ * Is the current page the last page?
+ *
+ * @return True if the current page is the last page or if only
+ * a single page exists.
+ */
+ public boolean isLastPage();
+
+ /**
+ * Is a page available after the current page?
+ *
+ * @return True if the next page is available
+ */
+ public boolean isNextPageAvailable();
+
+ /**
+ * Is a page available before the current page?
+ *
+ * @return True if the previous page is available
+ */
+ public boolean isPreviousPageAvailable();
+
+ /**
+ * Moves to the next page after the current page. If the current
+ * page is the last page, wrap to the first page.
+ *
+ * @return True if the page changed
+ */
+ public boolean nextPage();
+
+ /**
+ * Moves to the page before the current page. If the current
+ * page is the first page, wrap to the last page.
+ *
+ * @return True if the page changed
+ */
+ public boolean previousPage();
+
+ /**
+ * Moves to a specified page. If the specified
+ * page is beyond the last page, wrap to the first page.
+ * If the specified page is before the first page, wrap
+ * to the last page.
+ *
+ * @param pageNumber The page to go to
+ */
+ public void gotoPage(int pageNumber);
+
+ /**
+ * Returns the current page index, which is a zero based integer.
+ * All paginated list implementations should know what index they are
+ * on, even if they don't know the ultimate boundaries (min/max).
+ *
+ * @return The current page
+ */
+ public int getPageIndex();
+
+}
Added: ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/common/util/Stopwatch.java
URL: http://svn.apache.org/viewvc/ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/common/util/Stopwatch.java?rev=683745&view=auto
==============================================================================
--- ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/common/util/Stopwatch.java (added)
+++ ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/common/util/Stopwatch.java Thu Aug 7 16:21:46 2008
@@ -0,0 +1,226 @@
+package com.ibatis.common.util;
+
+import org.apache.ibatis.logging.*;
+
+import java.util.*;
+
+/**
+ * Stopwatch class used for testing.
+ */
+public class Stopwatch {
+
+ private static final Log log = LogFactory.getLog(Stopwatch.class);
+
+ private Map taskMap = new HashMap();
+
+ private String currentTaskName = null;
+ private long currentTaskTime = 0;
+
+ /**
+ * Get an iterator of the tasks
+ *
+ * @return - the Iterator
+ */
+ public Iterator getTaskNames() {
+ return taskMap.keySet().iterator();
+ }
+
+ /**
+ * Get the number of times assigned to a task
+ *
+ * @param taskName - the name of the task
+ * @return - the number of times
+ */
+ public long getTaskCount(String taskName) {
+ return ((TaskStat) taskMap.get(taskName)).getCount();
+ }
+
+ /**
+ * Get the total time added to a task
+ *
+ * @param taskName - the name of the task
+ * @return - the total time added to the task
+ */
+ public long getTotalTaskTime(String taskName) {
+ return ((TaskStat) taskMap.get(taskName)).getTotal();
+ }
+
+ /**
+ * Get the maximum time added to a task
+ *
+ * @param taskName - the name of the task
+ * @return - the maximum time added to a task
+ */
+ public long getMaxTaskTime(String taskName) {
+ return ((TaskStat) taskMap.get(taskName)).getMax();
+ }
+
+ /**
+ * Get the minimum time added to a task
+ *
+ * @param taskName - the name of the task
+ * @return - the minimum time added to a task
+ */
+ public long getMinTaskTime(String taskName) {
+ return ((TaskStat) taskMap.get(taskName)).getMin();
+ }
+
+ /**
+ * Get the average time added to a task
+ *
+ * @param taskName - the name of the task
+ * @return - the average time added to a task
+ */
+ public long getAvgTaskTime(String taskName) {
+ return ((TaskStat) taskMap.get(taskName)).getAverage();
+ }
+
+ /**
+ * Start (create) a task
+ *
+ * @param taskName - the name of the task
+ */
+ public void start(String taskName) {
+ if (log.isDebugEnabled()) {
+ log.debug("Starting: " + taskName);
+ }
+ this.currentTaskName = taskName;
+ currentTaskTime = System.currentTimeMillis();
+ }
+
+ /**
+ * Stop the timer on a task
+ */
+ public void stop() {
+ if (log.isDebugEnabled()) {
+ log.debug("Stopping: " + currentTaskName);
+ }
+ currentTaskTime = System.currentTimeMillis() - currentTaskTime;
+ appendTaskTime(currentTaskName, currentTaskTime);
+ }
+
+ private synchronized void appendTaskTime(String taskName, long taskTime) {
+ TaskStat stat = (TaskStat) taskMap.get(taskName);
+ if (stat == null) {
+ stat = new TaskStat();
+ taskMap.put(taskName, stat);
+ }
+ stat.appendTaskTime(taskTime);
+ }
+
+ /**
+ * Merge another StopWatch into this one
+ *
+ * @param watch - the StopWatch to merge into this one
+ */
+ public void mergeStopwatch(Stopwatch watch) {
+ Iterator names = watch.getTaskNames();
+ while (names.hasNext()) {
+ String name = (String) names.next();
+ long taskTime = watch.getTotalTaskTime(name);
+ appendTaskTime(name, taskTime);
+ }
+ }
+
+ /**
+ * Reset all of the timers in this StopWatch
+ */
+ public synchronized void reset() {
+ taskMap.clear();
+ }
+
+ public String toString() {
+ StringBuffer buffer = new StringBuffer();
+ buffer.append("Task,Count,Total,Max,Min,Avg\n");
+ Iterator names = getTaskNames();
+ while (names.hasNext()) {
+ String name = (String) names.next();
+ long taskCount = getTaskCount(name);
+ long taskTime = getTotalTaskTime(name);
+ long taskMin = getMinTaskTime(name);
+ long taskMax = getMaxTaskTime(name);
+ long taskAvg = getAvgTaskTime(name);
+ buffer.append(name + "," + taskCount + "," + taskTime + "," + taskMax + "," + taskMin + "," + taskAvg + "\n");
+ }
+ return buffer.toString();
+ }
+
+ private class TaskStat {
+ private static final long UNSET = -999999;
+
+ private long count = 0;
+ private long total = 0;
+ private long min = UNSET;
+ private long max = UNSET;
+
+ /**
+ * Add some time to a task
+ *
+ * @param taskTime - the time to add
+ */
+ public void appendTaskTime(long taskTime) {
+ count++;
+ total += taskTime;
+ if (max == UNSET || taskTime > max) {
+ max = taskTime;
+ }
+ if (min == UNSET || taskTime < min) {
+ min = taskTime;
+ }
+ }
+
+ /**
+ * Get the total time for the task
+ *
+ * @return - the total time
+ */
+ public long getTotal() {
+ return total;
+ }
+
+ /**
+ * Get the maximum of the times added to the task
+ *
+ * @return - the max value
+ */
+ public long getMax() {
+ return max;
+ }
+
+ /**
+ * Get the minimum of the times added to the task
+ *
+ * @return - the minimum value
+ */
+ public long getMin() {
+ return min;
+ }
+
+ /**
+ * Get the number of times added to the task
+ *
+ * @return - the number of times
+ */
+ public long getCount() {
+ return count;
+ }
+
+ /**
+ * Get the average of the times added to the task
+ *
+ * @return - the average
+ */
+ public long getAverage() {
+ if (count > 0) {
+ return Math.round((double) total / (double) count);
+ } else {
+ return 0;
+ }
+ }
+
+ }
+
+}
+
+
+
Added: ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/Dao.java
URL: http://svn.apache.org/viewvc/ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/Dao.java?rev=683745&view=auto
==============================================================================
--- ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/Dao.java (added)
+++ ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/Dao.java Thu Aug 7 16:21:46 2008
@@ -0,0 +1,16 @@
+package com.ibatis.dao.client;
+
+/**
+ * The interface that identifies and describes Data Access Objects.
+ * <p/>
+ * No methods are declared by this interface. However, if you provide
+ * a constructor with a single parameter of type DaoManager,
+ * that constructor will be used to instantiate the Dao such and
+ * the managing DaoManager instance will be passed in as a parameter.
+ * The DaoManager instance will allow you to easily access transactions
+ * and other DAOs.
+ * <p/>
+ */
+public interface Dao {
+
+}
Added: ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/DaoException.java
URL: http://svn.apache.org/viewvc/ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/DaoException.java?rev=683745&view=auto
==============================================================================
--- ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/DaoException.java (added)
+++ ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/DaoException.java Thu Aug 7 16:21:46 2008
@@ -0,0 +1,25 @@
+package com.ibatis.dao.client;
+
+/**
+ * General runtime exception thrown by the DAO framework.
+ * <p/>
+ * <p/>
+ */
+public class DaoException extends RuntimeException {
+
+ public DaoException() {
+ }
+
+ public DaoException(String msg) {
+ super(msg);
+ }
+
+ public DaoException(Throwable cause) {
+ super(cause);
+ }
+
+ public DaoException(String msg, Throwable cause) {
+ super(msg, cause);
+ }
+
+}
Added: ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/DaoManager.java
URL: http://svn.apache.org/viewvc/ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/DaoManager.java?rev=683745&view=auto
==============================================================================
--- ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/DaoManager.java (added)
+++ ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/DaoManager.java Thu Aug 7 16:21:46 2008
@@ -0,0 +1,120 @@
+package com.ibatis.dao.client;
+
+/**
+ * This interface describes the DaoManager interface. It provides
+ * access to all DAOs it manages and also allows transactions
+ * to be committed and ended (possibly rolled back).
+ * <p/>
+ * DAO instances returned from the DAO Manager are proxied such that transactions
+ * can be automatically started, committed and ended (or rolled back). This is
+ * a similar semantic to the JDBC autocommit, but much more powerful.
+ * <p/>
+ * Alternatively, tranasctions can be controlled programmatically, allowing you to
+ * demarcate wider scope transactions as needed.
+ * <p/>
+ * Either way, transactions will only be started for those contexts that require them.
+ * No unneccessary transactions will be started. When commitTransaction() and
+ * endTransaction() are called, all transactions which have been started in each
+ * configured context will be committed and ended respectively. endTransaction() will
+ * automatically rollback any transactions that have not been committed.
+ * <p/>
+ * Here's a couple of examples:
+ * <p/>
+ * <p/>
+ * <p/>
+ * <pre>
+ * <p/>
+ * // **************************************************************
+ * // AUTO COMMIT TRANASACTION SEMANTIC
+ * // **************************************************************
+ * <p/>
+ * DaoManager daoManager = DaoManagerBuilder.buildDaoManager(reader);
+ * PersonDao personDao = daoManager.getDao(PersonDao.class);
+ * // A transaction will be automatically started committed and ended
+ * // by calling any method on the DAO. The following insert and update
+ * // are TWO separate transactions.
+ * personDao.insertPerson (person); // Starts transaction
+ * person.setLastName("Begin");
+ * personDao.updatePerson (person); // Starts a new transaction
+ * <p/>
+ * // **************************************************************
+ * // PROGRAMMATIC DEMARCATION OF TRANSACTION SCOPE
+ * // **************************************************************
+ * <p/>
+ * DaoManager daoManager = DaoManagerBuilder.buildDaoManager(reader);
+ * PersonDao personDao = daoManager.getDao(PersonDao.class);
+ * try {
+ * // Calling startTransaction() tells the DAO Manager that you
+ * // are going to be managing the transactions manually.
+ * daoManager.startTransaction();
+ * personDao.insertPerson (person);
+ * person.setLastName("Begin");
+ * personDao.updatePerson (person);
+ * // Commit all active transactions in all contexts
+ * daoManager.commitTransaction();
+ * } finally {
+ * // End all active transactions in all contexts and rollback if necessary.
+ * daoManager.endTransaction();
+ * }
+ * </pre>
+ * <p/>
+ * <b>Important: </b> In order to achieve global transaction behaviour
+ * (i.e. two phase commit), you'll need to configure all of your contexts
+ * using JTA, JNDI and XA compliant DataSources.
+ * <p/>
+ */
+public interface DaoManager {
+
+ /**
+ * Gets a Dao instance for the requested interface type.
+ *
+ * @param type The interface or generic type for which an implementation
+ * should be returned.
+ * @return The Dao implementation instance.
+ */
+ public Dao getDao(Class type);
+
+ /**
+ * Gets a Dao instance for the requested interface type registered
+ * under the context with the specified id.
+ *
+ * @param iface The interface or generic type for which an implementation
+ * should be returned.
+ * @param contextId The ID of the context under which to find the DAO
+ * implementation (use for multiple interface defs).
+ * @return The Dao implementation instance.
+ */
+ public Dao getDao(Class iface, String contextId);
+
+ /**
+ * Gets the transaction that the provided Dao is currently working
+ * under. If there is no current transaction in scope, one will
+ * be started.
+ *
+ * @param dao The Dao to find a transaction for.
+ * @return The Transaction under which the Dao provided is working
+ * under.
+ */
+ public DaoTransaction getTransaction(Dao dao);
+
+ /**
+ * Starts a transaction scope managed by this DaoManager.
+ * If this method isn't called, then all DAO methods use
+ * "autocommit" semantics.
+ */
+ public void startTransaction();
+
+ /**
+ * Commits all transactions currently started for all DAO contexts
+ * managed by this DaoManager.
+ */
+ public void commitTransaction();
+
+ /**
+ * Ends all transactions currently started for all DAO contexts
+ * managed by this DaoManager. If any transactions have not been
+ * successfully committed, then those remaining will be rolled back.
+ */
+ public void endTransaction();
+
+}
Added: ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/DaoManagerBuilder.java
URL: http://svn.apache.org/viewvc/ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/DaoManagerBuilder.java?rev=683745&view=auto
==============================================================================
--- ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/DaoManagerBuilder.java (added)
+++ ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/DaoManagerBuilder.java Thu Aug 7 16:21:46 2008
@@ -0,0 +1,48 @@
+package com.ibatis.dao.client;
+
+import com.ibatis.dao.engine.builder.xml.XmlDaoManagerBuilder;
+
+import java.io.Reader;
+import java.util.Properties;
+
+/**
+ * Builds a DaoManager given a Reader (dao.xml) and optionally a set of
+ * properties. The following is an example of a dao.xml file.
+ * <ul>
+ * <li> <a href="dao.txt">The DAO Configuration file (dao.xml)</a>
+ * <ul>
+ * <p/>
+ */
+public class DaoManagerBuilder {
+
+ /**
+ * No instantiation allowed.
+ */
+ private DaoManagerBuilder() {
+ }
+
+ /**
+ * Builds a DAO Manager from the reader supplied.
+ *
+ * @param reader A Reader instance that reads a DAO configuration file (dao.xml).
+ * @param props A Properties instance that will be used for parameter substitution
+ * in the DAO configuration file (dao.xml).
+ * @return A configured DaoManager instance
+ */
+ public static DaoManager buildDaoManager(Reader reader, Properties props)
+ throws DaoException {
+ return new XmlDaoManagerBuilder().buildDaoManager(reader, props);
+ }
+
+ /**
+ * Builds a DAO Manager from the reader supplied.
+ *
+ * @param reader A Reader instance that reads a DAO configuration file (dao.xml).
+ * @return A configured DaoManager instance
+ */
+ public static DaoManager buildDaoManager(Reader reader) {
+ return new XmlDaoManagerBuilder().buildDaoManager(reader);
+ }
+
+
+}
Added: ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/DaoTransaction.java
URL: http://svn.apache.org/viewvc/ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/DaoTransaction.java?rev=683745&view=auto
==============================================================================
--- ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/DaoTransaction.java (added)
+++ ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/DaoTransaction.java Thu Aug 7 16:21:46 2008
@@ -0,0 +1,17 @@
+package com.ibatis.dao.client;
+
+/**
+ * This interface marks a class as being a DaoTransaction. Some examples
+ * of DAO Transaction implementations would be JDBC, JTA, SQL Map and
+ * Hibernate.
+ * <p/>
+ * No methods are declared by this interface, but DAO templates are
+ * provided to simplify accessing implementation specific transaction
+ * artifacts such as JDBC connections etc.
+ * <p/>
+ *
+ * @see com.ibatis.dao.client.template.DaoTemplate
+ */
+public interface DaoTransaction {
+
+}
Added: ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/template/DaoTemplate.java
URL: http://svn.apache.org/viewvc/ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/template/DaoTemplate.java?rev=683745&view=auto
==============================================================================
--- ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/template/DaoTemplate.java (added)
+++ ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/template/DaoTemplate.java Thu Aug 7 16:21:46 2008
@@ -0,0 +1,23 @@
+package com.ibatis.dao.client.template;
+
+import com.ibatis.dao.client.*;
+
+/**
+ * A base class for Dao implementations, or other DAO templates.
+ */
+public abstract class DaoTemplate implements Dao {
+
+ protected DaoManager daoManager;
+
+ /**
+ * The DaoManager that manages this Dao instance will be passed
+ * in as the parameter to this constructor automatically upon
+ * instantiation.
+ *
+ * @param daoManager
+ */
+ public DaoTemplate(DaoManager daoManager) {
+ this.daoManager = daoManager;
+ }
+
+}
Added: ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/template/JdbcDaoTemplate.java
URL: http://svn.apache.org/viewvc/ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/template/JdbcDaoTemplate.java?rev=683745&view=auto
==============================================================================
--- ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/template/JdbcDaoTemplate.java (added)
+++ ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/template/JdbcDaoTemplate.java Thu Aug 7 16:21:46 2008
@@ -0,0 +1,45 @@
+package com.ibatis.dao.client.template;
+
+import com.ibatis.dao.client.*;
+import com.ibatis.dao.engine.transaction.ConnectionDaoTransaction;
+
+import java.sql.Connection;
+
+/**
+ * A DaoTemplate for JDBC implementations that provides a
+ * convenient method to access the JDBC Connection.
+ * <p/>
+ * Use this template for both JDBC and JTA transaction managers.
+ * It can also be used for any transaction manager that supports
+ * normal JDBC connections, including iBATIS SQL Maps and Hibernate.
+ */
+public abstract class JdbcDaoTemplate extends DaoTemplate {
+
+ /**
+ * The DaoManager that manages this Dao instance will be passed
+ * in as the parameter to this constructor automatically upon
+ * instantiation.
+ *
+ * @param daoManager
+ */
+ public JdbcDaoTemplate(DaoManager daoManager) {
+ super(daoManager);
+ }
+
+ /**
+ * Gets the JDBC Connection associated with the current
+ * DaoTransaction that this Dao is working under.
+ *
+ * @return A JDBC Connection instance.
+ */
+ protected Connection getConnection() {
+ DaoTransaction trans = daoManager.getTransaction(this);
+ if (!(trans instanceof ConnectionDaoTransaction)) {
+ throw new DaoException("The DAO manager of type " + daoManager.getClass().getName() +
+ " cannot supply a JDBC Connection for this template, and is therefore not" +
+ "supported by JdbcDaoTemplate.");
+ }
+ return ((ConnectionDaoTransaction) trans).getConnection();
+ }
+
+}
Added: ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/template/SqlMapDaoTemplate.java
URL: http://svn.apache.org/viewvc/ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/template/SqlMapDaoTemplate.java?rev=683745&view=auto
==============================================================================
--- ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/template/SqlMapDaoTemplate.java (added)
+++ ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/client/template/SqlMapDaoTemplate.java Thu Aug 7 16:21:46 2008
@@ -0,0 +1,500 @@
+package com.ibatis.dao.client.template;
+
+import com.ibatis.common.util.PaginatedList;
+import com.ibatis.dao.client.*;
+import com.ibatis.dao.engine.transaction.sqlmap.SqlMapDaoTransaction;
+import com.ibatis.sqlmap.client.*;
+import com.ibatis.sqlmap.client.event.RowHandler;
+import com.ibatis.sqlmap.engine.execution.BatchException;
+
+import java.sql.SQLException;
+import java.util.*;
+
+/**
+ * A DaoTemplate for SQL Map implementations that provides a
+ * convenient method to access the SqlMapExecutor. This class
+ * also provides SqlMapExecutor method wrappers that conveniently
+ * wrap SQLExceptions with DAO Exceptions.
+ *
+ * @author Zach Scott
+ */
+public abstract class SqlMapDaoTemplate extends DaoTemplate implements SqlMapExecutor {
+
+ /**
+ * The DaoManager that manages this Dao instance will be passed
+ * in as the parameter to this constructor automatically upon
+ * instantiation.
+ *
+ * @param daoManager
+ */
+ public SqlMapDaoTemplate(DaoManager daoManager) {
+ super(daoManager);
+ }
+
+ /**
+ * Gets the SQL Map Executor associated with the current
+ * DaoTransaction that this Dao is working under. The SqlMapExecutor
+ * interface declares a number of methods for executing statements
+ * via an SqlMapClient instance.
+ *
+ * @return A SqlMapExecutor instance.
+ */
+ protected SqlMapExecutor getSqlMapExecutor() {
+ SqlMapDaoTransaction trans = (SqlMapDaoTransaction) daoManager.getTransaction(this);
+ return trans.getSqlMap();
+ }
+
+ /**
+ * Gets the SQL Map Transaction Manager associated with the current
+ * DaoTransaction that this Dao is working under. The SqlMapExecutor
+ * interface declares a number of methods for executing statements
+ * via an SqlMapClient instance.
+ * <p/>
+ * NOTE: It is rare to require this in a DAO. Only very special
+ * cases of DAO implementations will require access to the
+ * SqlMapTransactionManager. Messing with transactions at this
+ * level might be dangerous to your data integrity (e.g. committing
+ * too early).
+ *
+ * @return A SqlMapTransactionManager instance.
+ */
+ protected SqlMapTransactionManager getSqlMapTransactionManager() {
+ SqlMapDaoTransaction trans = (SqlMapDaoTransaction) daoManager.getTransaction(this);
+ return trans.getSqlMap();
+ }
+
+ /**
+ * Executes a mapped SQL INSERT statement.
+ * Insert is a bit different from other update methods, as it
+ * provides facilities for returning the primary key of the
+ * newly inserted row (rather than the effected rows). This
+ * functionality is of course optional.
+ * <p/>
+ * The parameter object is generally used to supply the input
+ * data for the INSERT values.
+ *
+ * @param id The name of the statement to execute.
+ * @param parameterObject The parameter object (e.g. JavaBean, Map, XML etc.).
+ * @return The primary key of the newly inserted row. This might be automatically
+ * generated by the RDBMS, or selected from a sequence table or other source.
+ */
+ public Object insert(String id, Object parameterObject) {
+ try {
+ return getSqlMapExecutor().insert(id, parameterObject);
+ } catch (SQLException e) {
+ throw new DaoException("Failed to insert - id ["
+ + id + "], parameterObject [" + parameterObject + "]. Cause: " + e, e);
+ }
+ }
+
+ /**
+ * Executes a mapped SQL INSERT statement.
+ * Insert is a bit different from other update methods, as it
+ * provides facilities for returning the primary key of the
+ * newly inserted row (rather than the effected rows). This
+ * functionality is of course optional.
+ * <p/>
+ * This overload assumes no parameter is needed.
+ *
+ * @param id The name of the statement to execute.
+ * @return The primary key of the newly inserted row. This might be automatically
+ * generated by the RDBMS, or selected from a sequence table or other source.
+ */
+ public Object insert(String id) {
+ try {
+ return getSqlMapExecutor().insert(id);
+ } catch (SQLException e) {
+ throw new DaoException("Failed to insert - id ["
+ + id + "]. Cause: " + e, e);
+ }
+ }
+
+ /**
+ * Executes a mapped SQL UPDATE statement.
+ * Update can also be used for any other update statement type,
+ * such as inserts and deletes. Update returns the number of
+ * rows effected.
+ * <p/>
+ * The parameter object is generally used to supply the input
+ * data for the UPDATE values as well as the WHERE clause parameter(s).
+ *
+ * @param id The name of the statement to execute.
+ * @param parameterObject The parameter object (e.g. JavaBean, Map, XML etc.).
+ * @return The number of rows effected.
+ */
+ public int update(String id, Object parameterObject) {
+ try {
+ return getSqlMapExecutor().update(id, parameterObject);
+ } catch (SQLException e) {
+ throw new DaoException("Failed to update - id ["
+ + id + "] - parameterObject [" + parameterObject + "]. Cause: " + e, e);
+ }
+ }
+
+ /**
+ * Executes a mapped SQL UPDATE statement.
+ * Update can also be used for any other update statement type,
+ * such as inserts and deletes. Update returns the number of
+ * rows effected.
+ * <p/>
+ * This overload assumes no parameter is needed.
+ *
+ * @param id The name of the statement to execute.
+ * @return The number of rows effected.
+ */
+ public int update(String id) {
+ try {
+ return getSqlMapExecutor().update(id);
+ } catch (SQLException e) {
+ throw new DaoException("Failed to update - id ["
+ + id + "]. Cause: " + e, e);
+ }
+ }
+
+ /**
+ * Executes a mapped SQL DELETE statement.
+ * Delete returns the number of rows effected.
+ * <p/>
+ * The parameter object is generally used to supply the input
+ * data for the WHERE clause parameter(s) of the DELETE statement.
+ *
+ * @param id The name of the statement to execute.
+ * @param parameterObject The parameter object (e.g. JavaBean, Map, XML etc.).
+ * @return The number of rows effected.
+ */
+ public int delete(String id, Object parameterObject) {
+ try {
+ return getSqlMapExecutor().delete(id, parameterObject);
+ } catch (SQLException e) {
+ throw new DaoException("Failed to delete - id ["
+ + id + "] - parameterObject [" + parameterObject + "]. Cause: " + e, e);
+ }
+ }
+
+ /**
+ * Executes a mapped SQL DELETE statement.
+ * Delete returns the number of rows effected.
+ * <p/>
+ * This overload assumes no parameter is needed.
+ *
+ * @param id The name of the statement to execute.
+ * @return The number of rows effected.
+ */
+ public int delete(String id) {
+ try {
+ return getSqlMapExecutor().delete(id);
+ } catch (SQLException e) {
+ throw new DaoException("Failed to delete - id ["
+ + id + "]. Cause: " + e, e);
+ }
+ }
+
+ /**
+ * Executes a mapped SQL SELECT statement that returns data to populate
+ * a single object instance.
+ * <p/>
+ * The parameter object is generally used to supply the input
+ * data for the WHERE clause parameter(s) of the SELECT statement.
+ *
+ * @param id The name of the statement to execute.
+ * @param parameterObject The parameter object (e.g. JavaBean, Map, XML etc.).
+ * @return The single result object populated with the result set data.
+ */
+ public Object queryForObject(String id, Object parameterObject) {
+ try {
+ return getSqlMapExecutor().queryForObject(id, parameterObject);
+ } catch (SQLException e) {
+ throw new DaoException("Failed to execute queryForObject - id ["
+ + id + "], parameterObject [" + parameterObject + "]. Cause: " + e, e);
+ }
+ }
+
+ /**
+ * Executes a mapped SQL SELECT statement that returns data to populate
+ * a single object instance.
+ * <p/>
+ * This overload assumes no parameter is needed.
+ *
+ * @param id The name of the statement to execute.
+ * @return The single result object populated with the result set data.
+ */
+ public Object queryForObject(String id) {
+ try {
+ return getSqlMapExecutor().queryForObject(id);
+ } catch (SQLException e) {
+ throw new DaoException("Failed to execute queryForObject - id ["
+ + id + "]. Cause: " + e, e);
+ }
+ }
+
+ /**
+ * Executes a mapped SQL SELECT statement that returns data to populate
+ * the supplied result object.
+ * <p/>
+ * The parameter object is generally used to supply the input
+ * data for the WHERE clause parameter(s) of the SELECT statement.
+ *
+ * @param id The name of the statement to execute.
+ * @param parameterObject The parameter object (e.g. JavaBean, Map, XML etc.).
+ * @param resultObject The result object instance that should be populated with result data.
+ * @return The single result object as supplied by the resultObject parameter, populated with the result set data.
+ */
+ public Object queryForObject(String id, Object parameterObject, Object resultObject) {
+ try {
+ return getSqlMapExecutor().queryForObject(id, parameterObject, resultObject);
+ } catch (SQLException e) {
+ throw new DaoException("Failed to queryForObject - id ["
+ + id + "], parameterObject [" + parameterObject + "]. Cause: " + e, e);
+ }
+ }
+
+ /**
+ * Executes a mapped SQL SELECT statement that returns data to populate
+ * a number of result objects.
+ * <p/>
+ * The parameter object is generally used to supply the input
+ * data for the WHERE clause parameter(s) of the SELECT statement.
+ *
+ * @param id The name of the statement to execute.
+ * @param parameterObject The parameter object (e.g. JavaBean, Map, XML etc.).
+ * @return A List of result objects.
+ */
+ public List queryForList(String id, Object parameterObject) {
+ try {
+ return getSqlMapExecutor().queryForList(id, parameterObject);
+ } catch (SQLException e) {
+ throw new DaoException("Failed to queryForList - id ["
+ + id + "], parameterObject [" + parameterObject + "]. Cause: " + e, e);
+ }
+ }
+
+ /**
+ * Executes a mapped SQL SELECT statement that returns data to populate
+ * a number of result objects.
+ * <p/>
+ * This overload assumes no parameter is needed.
+ *
+ * @param id The name of the statement to execute.
+ * @return A List of result objects.
+ */
+ public List queryForList(String id) {
+ try {
+ return getSqlMapExecutor().queryForList(id);
+ } catch (SQLException e) {
+ throw new DaoException("Failed to queryForList - id ["
+ + id + "]. Cause: " + e, e);
+ }
+ }
+
+ /**
+ * Executes a mapped SQL SELECT statement that returns data to populate
+ * a number of result objects within a certain range.
+ * <p/>
+ * The parameter object is generally used to supply the input
+ * data for the WHERE clause parameter(s) of the SELECT statement.
+ *
+ * @param id The name of the statement to execute.
+ * @param parameterObject The parameter object (e.g. JavaBean, Map, XML etc.).
+ * @param skip The number of results to ignore.
+ * @param max The maximum number of results to return.
+ * @return A List of result objects.
+ */
+ public List queryForList(String id, Object parameterObject, int skip, int max) {
+ try {
+ return getSqlMapExecutor().queryForList(id, parameterObject, skip, max);
+ } catch (SQLException e) {
+ throw new DaoException("Failed to queryForList - id ["
+ + id + "], parameterObject [" + parameterObject + "], skip ["
+ + skip + "], max [" + max + "]. Cause: " + e, e);
+ }
+ }
+
+ /**
+ * Executes a mapped SQL SELECT statement that returns data to populate
+ * a number of result objects within a certain range.
+ * <p/>
+ * This overload assumes no parameter is needed.
+ *
+ * @param id The name of the statement to execute.
+ * @param skip The number of results to ignore.
+ * @param max The maximum number of results to return.
+ * @return A List of result objects.
+ */
+ public List queryForList(String id, int skip, int max) {
+ try {
+ return getSqlMapExecutor().queryForList(id, skip, max);
+ } catch (SQLException e) {
+ throw new DaoException("Failed to queryForList - id ["
+ + id + "], skip ["
+ + skip + "], max [" + max + "]. Cause: " + e, e);
+ }
+ }
+
+ /**
+ * Executes a mapped SQL SELECT statement that returns data to populate
+ * a number of result objects that will be handled one at a time by a
+ * RowHandler.
+ * <p/>
+ * This is generally a good approach to take when dealing with large sets
+ * of records (i.e. hundreds, thousands...) that need to be processed without
+ * eating up all of the system resources.
+ * <p/>
+ * The parameter object is generally used to supply the input
+ * data for the WHERE clause parameter(s) of the SELECT statement.
+ *
+ * @param id The name of the statement to execute.
+ * @param parameterObject The parameter object (e.g. JavaBean, Map, XML etc.).
+ * @param rowHandler A RowHandler instance
+ */
+ public void queryWithRowHandler(String id, Object parameterObject, RowHandler rowHandler) {
+ try {
+ getSqlMapExecutor().queryWithRowHandler(id, parameterObject, rowHandler);
+ } catch (SQLException e) {
+ throw new DaoException("Failed to queryForList - id [" + id + "], parameterObject ["
+ + parameterObject + "], rowHandler [ " + rowHandler + "]. Cause: " + e, e);
+ }
+ }
+
+ /**
+ * Executes a mapped SQL SELECT statement that returns data to populate
+ * a number of result objects that will be handled one at a time by a
+ * RowHandler.
+ * <p/>
+ * This is generally a good approach to take when dealing with large sets
+ * of records (i.e. hundreds, thousands...) that need to be processed without
+ * eating up all of the system resources.
+ * <p/>
+ * This overload assumes no parameter is needed.
+ *
+ * @param id The name of the statement to execute.
+ * @param rowHandler A RowHandler instance
+ */
+ public void queryWithRowHandler(String id, RowHandler rowHandler) {
+ try {
+ getSqlMapExecutor().queryWithRowHandler(id, rowHandler);
+ } catch (SQLException e) {
+ throw new DaoException("Failed to queryForList - id [" + id + "], rowHandler [ "
+ + rowHandler + "]. Cause: " + e, e);
+ }
+ }
+
+ /**
+ * Executes a mapped SQL SELECT statement that returns data to populate
+ * a number of result objects a page at a time.
+ * <p/>
+ * The parameter object is generally used to supply the input
+ * data for the WHERE clause parameter(s) of the SELECT statement.
+ *
+ * @param id The name of the statement to execute.
+ * @param parameterObject The parameter object (e.g. JavaBean, Map, XML etc.).
+ * @param pageSize The maximum number of result objects each page can hold.
+ * @return A PaginatedList of result objects.
+ */
+ public PaginatedList queryForPaginatedList(String id, Object parameterObject, int pageSize) {
+ try {
+ return getSqlMapExecutor().queryForPaginatedList(id, parameterObject, pageSize);
+ } catch (SQLException e) {
+ throw new DaoException("Failed to queryForPaginatedList - id [" + id + "], parameterObject ["
+ + parameterObject + "], pageSize [" + pageSize + "]. Cause: " + e, e);
+ }
+ }
+
+ /**
+ * Executes a mapped SQL SELECT statement that returns data to populate
+ * a number of result objects a page at a time.
+ * <p/>
+ * This overload assumes no parameter is needed.
+ *
+ * @param id The name of the statement to execute.
+ * @param pageSize The maximum number of result objects each page can hold.
+ * @return A PaginatedList of result objects.
+ */
+ public PaginatedList queryForPaginatedList(String id, int pageSize) {
+ return queryForPaginatedList(id, null, pageSize);
+ }
+
+ /**
+ * Executes a mapped SQL SELECT statement that returns data to populate
+ * a number of result objects that will be keyed into a Map.
+ * <p/>
+ * The parameter object is generally used to supply the input
+ * data for the WHERE clause parameter(s) of the SELECT statement.
+ *
+ * @param id The name of the statement to execute.
+ * @param parameterObject The parameter object (e.g. JavaBean, Map, XML etc.).
+ * @param keyProp The property to be used as the key in the Map.
+ * @return A Map keyed by keyProp with values being the result object instance.
+ */
+ public Map queryForMap(String id, Object parameterObject, String keyProp) {
+ try {
+ return getSqlMapExecutor().queryForMap(id, parameterObject, keyProp);
+ } catch (SQLException e) {
+ throw new DaoException("Failed to queryForMap - id [" + id + "], parameterObject ["
+ + parameterObject + "], keyProp [" + keyProp + "]. Cause: " + e, e);
+ }
+ }
+
+ /**
+ * Executes a mapped SQL SELECT statement that returns data to populate
+ * a number of result objects from which one property will be keyed into a Map.
+ * <p/>
+ * The parameter object is generally used to supply the input
+ * data for the WHERE clause parameter(s) of the SELECT statement.
+ *
+ * @param id The name of the statement to execute.
+ * @param parameterObject The parameter object (e.g. JavaBean, Map, XML etc.).
+ * @param keyProp The property to be used as the key in the Map.
+ * @param valueProp The property to be used as the value in the Map.
+ * @return A Map keyed by keyProp with values of valueProp.
+ */
+ public Map queryForMap(String id, Object parameterObject, String keyProp, String valueProp) {
+ try {
+ return getSqlMapExecutor().queryForMap(id, parameterObject, keyProp, valueProp);
+ } catch (SQLException e) {
+ throw new DaoException("Failed to queryForMap - id [" + id + "], parameterObject ["
+ + parameterObject + "], keyProp [" + keyProp + "], valueProp ["
+ + valueProp + "]. Cause: " + e, e);
+ }
+ }
+
+ /**
+ * Starts a batch in which update statements will be cached before being sent to
+ * the database all at once. This can improve overall performance of updates update
+ * when dealing with numerous updates (e.g. inserting 1:M related data).
+ */
+ public void startBatch() {
+ try {
+ getSqlMapExecutor().startBatch();
+ } catch (SQLException e) {
+ throw new DaoException("Failed to startBatch. Cause: " + e, e);
+ }
+ }
+
+ /**
+ * Executes (flushes) all statements currently batched.
+ */
+ public int executeBatch() {
+ try {
+ return getSqlMapExecutor().executeBatch();
+ } catch (SQLException e) {
+ throw new DaoException("Failed to executeBatch. Cause: " + e, e);
+ }
+ }
+
+ /**
+ * Executes (flushes) all statements currently batched.
+ *
+ * @return a List of BatchResult objects. There will be one element in the
+ * list for each sub-batch executed. A sub-batch is created by adding a statement
+ * to the batch that does not equal the prior statement.
+ */
+ public List executeBatchDetailed() {
+ try {
+ return getSqlMapExecutor().executeBatchDetailed();
+ } catch (BatchException e) {
+ throw new DaoException("Failed to executeBatch. Cause: " + e, e);
+ } catch (SQLException e) {
+ throw new DaoException("Failed to executeBatch. Cause: " + e, e);
+ }
+ }
+}
Added: ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/builder/xml/DaoClasspathEntityResolver.java
URL: http://svn.apache.org/viewvc/ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/builder/xml/DaoClasspathEntityResolver.java?rev=683745&view=auto
==============================================================================
--- ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/builder/xml/DaoClasspathEntityResolver.java (added)
+++ ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/builder/xml/DaoClasspathEntityResolver.java Thu Aug 7 16:21:46 2008
@@ -0,0 +1,62 @@
+package com.ibatis.dao.engine.builder.xml;
+
+import com.ibatis.common.resources.Resources;
+import org.xml.sax.*;
+
+import java.io.*;
+import java.util.*;
+
+public class DaoClasspathEntityResolver implements EntityResolver {
+
+ private static final String DTD_PATH_DAO = "com/ibatis/dao/engine/builder/xml/dao-2.dtd";
+
+ private static final Map doctypeMap = new HashMap();
+
+ static {
+ doctypeMap.put("http://www.ibatis.com/dtd/dao-2.dtd", DTD_PATH_DAO);
+ doctypeMap.put("http://ibatis.apache.org/dtd/dao-2.dtd", DTD_PATH_DAO);
+ doctypeMap.put("-//iBATIS.com//DTD DAO Configuration 2.0", DTD_PATH_DAO);
+ doctypeMap.put("-//iBATIS.com//DTD DAO Config 2.0", DTD_PATH_DAO);
+ }
+
+
+ /**
+ * Converts a public DTD into a local one
+ *
+ * @param publicId Unused but required by EntityResolver interface
+ * @param systemId The DTD that is being requested
+ * @return The InputSource for the DTD
+ * @throws org.xml.sax.SAXException If anything goes wrong
+ */
+ public InputSource resolveEntity(String publicId, String systemId)
+ throws SAXException {
+ InputSource source = null;
+
+ try {
+ String path = (String) doctypeMap.get(publicId);
+ source = getInputSource(path, source);
+ if (source == null) {
+ path = (String) doctypeMap.get(systemId);
+ source = getInputSource(path, source);
+ }
+ } catch (Exception e) {
+ throw new SAXException(e.toString());
+ }
+
+ return source;
+ }
+
+ private InputSource getInputSource(String path, InputSource source) {
+ if (path != null) {
+ InputStream in = null;
+ try {
+ in = Resources.getResourceAsStream(path);
+ source = new InputSource(in);
+ } catch (IOException e) {
+ // ignore, null is ok
+ }
+ }
+ return source;
+ }
+
+}
Added: ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/builder/xml/XmlDaoManagerBuilder.java
URL: http://svn.apache.org/viewvc/ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/builder/xml/XmlDaoManagerBuilder.java?rev=683745&view=auto
==============================================================================
--- ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/builder/xml/XmlDaoManagerBuilder.java (added)
+++ ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/builder/xml/XmlDaoManagerBuilder.java Thu Aug 7 16:21:46 2008
@@ -0,0 +1,350 @@
+package com.ibatis.dao.engine.builder.xml;
+
+
+import com.ibatis.common.resources.Resources;
+import com.ibatis.dao.client.*;
+import com.ibatis.dao.engine.impl.*;
+import com.ibatis.dao.engine.transaction.DaoTransactionManager;
+import com.ibatis.dao.engine.transaction.external.ExternalDaoTransactionManager;
+import com.ibatis.dao.engine.transaction.jdbc.JdbcDaoTransactionManager;
+import com.ibatis.dao.engine.transaction.sqlmap.SqlMapDaoTransactionManager;
+import org.w3c.dom.*;
+import org.xml.sax.*;
+
+import javax.xml.parsers.*;
+import java.io.*;
+import java.lang.reflect.Constructor;
+import java.util.*;
+
+/**
+ * NOT THREAD SAFE. USE SEPARATE INSTANCES PER THREAD.
+ */
+public class XmlDaoManagerBuilder {
+
+
+ private static final String DAO_CONFIG_ELEMENT = "daoConfig";
+ private static final String PROPERTIES_ELEMENT = "properties";
+ private static final String CONTEXT_ELEMENT = "context";
+ private static final String TRANS_MGR_ELEMENT = "transactionManager";
+ private static final String PROPERTY_ELEMENT = "property";
+ private static final String DAO_ELEMENT = "dao";
+
+ private Properties properties = null;
+ private boolean validationEnabled = true;
+ private Map typeAliases = new HashMap();
+
+ public XmlDaoManagerBuilder() {
+ typeAliases.put("EXTERNAL", ExternalDaoTransactionManager.class.getName());
+ typeAliases.put("JDBC", JdbcDaoTransactionManager.class.getName());
+ typeAliases.put("SQLMAP", SqlMapDaoTransactionManager.class.getName());
+ }
+
+ public DaoManager buildDaoManager(Reader reader, Properties props)
+ throws DaoException {
+ properties = props;
+ return buildDaoManager(reader);
+ }
+
+ public DaoManager buildDaoManager(Reader reader)
+ throws DaoException {
+ StandardDaoManager daoManager = new StandardDaoManager();
+
+ try {
+
+ Document doc = getDoc(reader);
+ Element root = (Element) doc.getLastChild();
+
+ String rootname = root.getNodeName();
+ if (!DAO_CONFIG_ELEMENT.equals(rootname)) {
+ throw new IOException("Error while configuring DaoManager. The root tag of the DAO configuration XML " +
+ "document must be '" + DAO_CONFIG_ELEMENT + "'.");
+ }
+
+ NodeList children = root.getChildNodes();
+ for (int i = 0; i < children.getLength(); i++) {
+ Node child = children.item(i);
+ if (child.getNodeType() == Node.ELEMENT_NODE) {
+ if (CONTEXT_ELEMENT.equals(child.getNodeName())) {
+ DaoContext daoContext = parseContext((Element) child, daoManager);
+ daoManager.addContext(daoContext);
+ } else if (PROPERTIES_ELEMENT.equals(child.getNodeName())) {
+ Properties attributes = parseAttributes(child);
+ if (attributes.containsKey("resource")) {
+ String resource = attributes.getProperty("resource");
+ if (properties == null) {
+ properties = Resources.getResourceAsProperties(resource);
+ } else {
+ Properties tempProps = Resources.getResourceAsProperties(resource);
+ tempProps.putAll(properties);
+ properties = tempProps;
+ }
+ } else if (attributes.containsKey("url")) {
+ String url = attributes.getProperty("url");
+ if (properties == null) {
+ properties = Resources.getUrlAsProperties(url);
+ } else {
+ Properties tempProps = Resources.getUrlAsProperties(url);
+ tempProps.putAll(properties);
+ properties = tempProps;
+ }
+ }
+ }
+ }
+ }
+ } catch (Exception e) {
+ throw new DaoException("Error while configuring DaoManager. Cause: " + e.toString(), e);
+ }
+ return daoManager;
+ }
+
+ public boolean isValidationEnabled() {
+ return validationEnabled;
+ }
+
+ public void setValidationEnabled(boolean validationEnabled) {
+ this.validationEnabled = validationEnabled;
+ }
+
+ private DaoContext parseContext(Element contextElement, StandardDaoManager daoManager)
+ throws DaoException {
+ DaoContext daoContext = new DaoContext();
+
+ daoContext.setDaoManager(daoManager);
+ String id = contextElement.getAttribute("id");
+ if (id != null && id.length() > 0) {
+ daoContext.setId(id);
+ }
+
+ NodeList children = contextElement.getChildNodes();
+ for (int i = 0; i < children.getLength(); i++) {
+ Node child = children.item(i);
+ if (child.getNodeType() == Node.ELEMENT_NODE) {
+ if (TRANS_MGR_ELEMENT.equals(child.getNodeName())) {
+ DaoTransactionManager txMgr = parseTransactionManager((Element) child);
+ daoContext.setTransactionManager(txMgr);
+ } else if (DAO_ELEMENT.equals(child.getNodeName())) {
+ DaoImpl daoImpl = parseDao((Element) child, daoManager, daoContext);
+ daoContext.addDao(daoImpl);
+ }
+ }
+ }
+
+ return daoContext;
+ }
+
+ private DaoTransactionManager parseTransactionManager(Element transPoolElement)
+ throws DaoException {
+ DaoTransactionManager txMgr = null;
+
+ Properties attributes = parseAttributes(transPoolElement);
+
+ String implementation = attributes.getProperty("type");
+ implementation = resolveAlias(implementation);
+
+
+ try {
+ txMgr = (DaoTransactionManager) Resources.classForName(implementation).newInstance();
+ } catch (Exception e) {
+ throw new DaoException("Error while configuring DaoManager. Cause: " + e.toString(), e);
+ }
+
+ Properties props = properties;
+
+ if (props == null) {
+ props = parsePropertyElements(transPoolElement);
+ } else {
+ props.putAll(parsePropertyElements(transPoolElement));
+ }
+
+ txMgr.configure(props);
+
+ if (txMgr == null) {
+ throw new DaoException("Error while configuring DaoManager. Some unknown condition caused the " +
+ "DAO Transaction Manager to be null after configuration.");
+ }
+
+ return txMgr;
+ }
+
+ private DaoImpl parseDao(Element element, StandardDaoManager daoManager, DaoContext daoContext) {
+ DaoImpl daoImpl = new DaoImpl();
+ if (element.getNodeType() == Node.ELEMENT_NODE) {
+ if (DAO_ELEMENT.equals(element.getNodeName())) {
+
+ Properties attributes = parseAttributes(element);
+
+ try {
+ String iface = attributes.getProperty("interface");
+ String impl = attributes.getProperty("implementation");
+ daoImpl.setDaoManager(daoManager);
+ daoImpl.setDaoContext(daoContext);
+ daoImpl.setDaoInterface(Resources.classForName(iface));
+ daoImpl.setDaoImplementation(Resources.classForName(impl));
+
+ Class daoClass = daoImpl.getDaoImplementation();
+ Dao dao = null;
+
+ try {
+ Constructor constructor = daoClass.getConstructor(new Class[]{DaoManager.class});
+ dao = (Dao) constructor.newInstance(new Object[]{daoManager});
+ } catch (Exception e) {
+ dao = (Dao) daoClass.newInstance();
+ }
+
+ daoImpl.setDaoInstance(dao);
+ daoImpl.initProxy();
+ } catch (Exception e) {
+ throw new DaoException("Error configuring DAO. Cause: " + e, e);
+ }
+ }
+ }
+ return daoImpl;
+ }
+
+ private Properties parsePropertyElements(Element propsParentElement) {
+
+ Properties props = new Properties();
+
+ NodeList children = propsParentElement.getChildNodes();
+ for (int i = 0; i < children.getLength(); i++) {
+ Node child = children.item(i);
+
+ if (child.getNodeType() == Node.ELEMENT_NODE) {
+ if (PROPERTY_ELEMENT.equals(child.getNodeName())) {
+
+ Properties attributes = parseAttributes(child);
+
+ String name = attributes.getProperty("name");
+ String value = attributes.getProperty("value");
+
+ props.setProperty(name, value);
+ }
+ }
+
+ }
+
+ return props;
+ }
+
+ private Properties parseAttributes(Node n) {
+ Properties attributes = new Properties();
+ NamedNodeMap attributeNodes = n.getAttributes();
+ for (int i = 0; i < attributeNodes.getLength(); i++) {
+ Node attribute = attributeNodes.item(i);
+ String value = parsePropertyTokens(attribute.getNodeValue());
+ attributes.put(attribute.getNodeName(), value);
+ }
+ return attributes;
+ }
+
+ private String parsePropertyTokens(String string) {
+ final String OPEN = "${";
+ final String CLOSE = "}";
+ String newString = string;
+ if (newString != null && properties != null) {
+ int start = newString.indexOf(OPEN);
+ int end = newString.indexOf(CLOSE);
+
+ while (start > -1 && end > start) {
+ String prepend = newString.substring(0, start);
+ String append = newString.substring(end + CLOSE.length());
+ String propName = newString.substring(start + OPEN.length(), end);
+ String propValue = properties.getProperty(propName);
+ if (propValue == null) {
+ newString = prepend + append;
+ } else {
+ newString = prepend + propValue + append;
+ }
+ start = newString.indexOf(OPEN);
+ end = newString.indexOf(CLOSE);
+ }
+ }
+ return newString;
+ }
+
+ private Document getDoc(Reader reader) {
+ try {
+ // Configuration
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ dbf.setNamespaceAware(false);
+ dbf.setValidating(true);
+ dbf.setIgnoringComments(true);
+ dbf.setIgnoringElementContentWhitespace(true);
+ dbf.setCoalescing(false);
+ dbf.setExpandEntityReferences(false);
+
+ OutputStreamWriter errorWriter = new OutputStreamWriter(System.err);
+
+ DocumentBuilder db = dbf.newDocumentBuilder();
+ db.setErrorHandler(new SimpleErrorHandler(new PrintWriter(errorWriter, true)));
+ db.setEntityResolver(new DaoClasspathEntityResolver());
+
+ // Parse input file
+ Document doc = db.parse(new InputSource(reader));
+ return doc;
+ } catch (Exception e) {
+ throw new RuntimeException("XML Parser Error. Cause: " + e);
+ }
+ }
+
+ private String resolveAlias(String string) {
+ String newString = null;
+ if (typeAliases.containsKey(string)) {
+ newString = (String) typeAliases.get(string);
+ }
+ if (newString != null) {
+ string = newString;
+ }
+ return string;
+ }
+
+ /**
+ * **********************************
+ * ******* SimpleErrorHandler *******
+ * **********************************
+ */
+
+ // Error handler to report errors and warnings
+ private static class SimpleErrorHandler implements ErrorHandler {
+ /**
+ * Error handler output goes here
+ */
+ private PrintWriter out;
+
+ SimpleErrorHandler(PrintWriter out) {
+ this.out = out;
+ }
+
+ /**
+ * Returns a string describing parse exception details
+ */
+ private String getParseExceptionInfo(SAXParseException spe) {
+ String systemId = spe.getSystemId();
+ if (systemId == null) {
+ systemId = "null";
+ }
+ String info = "URI=" + systemId +
+ " Line=" + spe.getLineNumber() +
+ ": " + spe.getMessage();
+ return info;
+ }
+
+ // The following methods are standard SAX ErrorHandler methods.
+ // See SAX documentation for more info.
+
+ public void warning(SAXParseException spe) throws SAXException {
+ out.println("Warning: " + getParseExceptionInfo(spe));
+ }
+
+ public void error(SAXParseException spe) throws SAXException {
+ String message = "Error: " + getParseExceptionInfo(spe);
+ throw new SAXException(message);
+ }
+
+ public void fatalError(SAXParseException spe) throws SAXException {
+ String message = "Fatal Error: " + getParseExceptionInfo(spe);
+ throw new SAXException(message);
+ }
+ }
+
+}
Added: ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/builder/xml/dao-2.dtd
URL: http://svn.apache.org/viewvc/ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/builder/xml/dao-2.dtd?rev=683745&view=auto
==============================================================================
--- ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/builder/xml/dao-2.dtd (added)
+++ ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/builder/xml/dao-2.dtd Thu Aug 7 16:21:46 2008
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!ELEMENT daoConfig (properties? , context+)>
+
+<!ELEMENT context (transactionManager, dao*)+>
+<!ATTLIST context
+id CDATA #IMPLIED
+>
+
+<!ELEMENT properties EMPTY>
+<!ATTLIST properties
+resource CDATA #IMPLIED
+url CDATA #IMPLIED
+>
+
+<!ELEMENT transactionManager (property*)>
+<!ATTLIST transactionManager
+type CDATA #REQUIRED
+>
+
+<!ELEMENT property EMPTY>
+<!ATTLIST property
+name CDATA #REQUIRED
+value CDATA #REQUIRED
+>
+
+<!ELEMENT dao EMPTY>
+<!ATTLIST dao
+interface CDATA #REQUIRED
+implementation CDATA #REQUIRED
+>
Added: ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/impl/DaoContext.java
URL: http://svn.apache.org/viewvc/ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/impl/DaoContext.java?rev=683745&view=auto
==============================================================================
--- ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/impl/DaoContext.java (added)
+++ ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/impl/DaoContext.java Thu Aug 7 16:21:46 2008
@@ -0,0 +1,104 @@
+package com.ibatis.dao.engine.impl;
+
+import com.ibatis.dao.client.*;
+import com.ibatis.dao.engine.transaction.DaoTransactionManager;
+
+import java.util.*;
+
+public class DaoContext {
+
+ private String id;
+ private StandardDaoManager daoManager;
+ private DaoTransactionManager transactionManager;
+ private ThreadLocal transaction = new ThreadLocal();
+ private ThreadLocal state = new ThreadLocal();
+
+ private Map typeDaoImplMap = new HashMap();
+
+ public DaoContext() {
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public StandardDaoManager getDaoManager() {
+ return daoManager;
+ }
+
+ public void setDaoManager(StandardDaoManager daoManager) {
+ this.daoManager = daoManager;
+ }
+
+ public DaoTransactionManager getTransactionManager() {
+ return transactionManager;
+ }
+
+ public void setTransactionManager(DaoTransactionManager transactionManager) {
+ this.transactionManager = transactionManager;
+ }
+
+ public void addDao(DaoImpl daoImpl) {
+ if (typeDaoImplMap.containsKey(daoImpl.getDaoInterface())) {
+ throw new DaoException("More than one implementation for '" + daoImpl.getDaoInterface() + "' was configured. " +
+ "Only one implementation per context is allowed.");
+ }
+ typeDaoImplMap.put(daoImpl.getDaoInterface(), daoImpl);
+ }
+
+ public Dao getDao(Class iface) {
+ DaoImpl impl = (DaoImpl) typeDaoImplMap.get(iface);
+ if (impl == null) {
+ throw new DaoException("There is no DAO implementation found for " + iface + " in this context.");
+ }
+ return impl.getProxy();
+ }
+
+ public Iterator getDaoImpls() {
+ return typeDaoImplMap.values().iterator();
+ }
+
+ public DaoTransaction getTransaction() {
+ startTransaction();
+ return (DaoTransaction) transaction.get();
+ }
+
+ public void startTransaction() {
+ if (state.get() != DaoTransactionState.ACTIVE) {
+ DaoTransaction trans = transactionManager.startTransaction();
+ transaction.set(trans);
+ state.set(DaoTransactionState.ACTIVE);
+ daoManager.addContextInTransaction(this);
+ }
+ }
+
+ public void commitTransaction() {
+ DaoTransaction trans = (DaoTransaction) transaction.get();
+ if (state.get() == DaoTransactionState.ACTIVE) {
+ transactionManager.commitTransaction(trans);
+ state.set(DaoTransactionState.COMMITTED);
+ } else {
+ state.set(DaoTransactionState.INACTIVE);
+ }
+ }
+
+ public void endTransaction() {
+ DaoTransaction trans = (DaoTransaction) transaction.get();
+ if (state.get() == DaoTransactionState.ACTIVE) {
+ try {
+ transactionManager.rollbackTransaction(trans);
+ } finally {
+ state.set(DaoTransactionState.ROLLEDBACK);
+ transaction.set(null);
+ }
+ } else {
+ state.set(DaoTransactionState.INACTIVE);
+ transaction.set(null);
+ }
+ }
+
+}
Added: ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/impl/DaoImpl.java
URL: http://svn.apache.org/viewvc/ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/impl/DaoImpl.java?rev=683745&view=auto
==============================================================================
--- ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/impl/DaoImpl.java (added)
+++ ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/impl/DaoImpl.java Thu Aug 7 16:21:46 2008
@@ -0,0 +1,62 @@
+package com.ibatis.dao.engine.impl;
+
+import com.ibatis.dao.client.Dao;
+
+public class DaoImpl {
+
+ private StandardDaoManager daoManager;
+ private DaoContext daoContext;
+ private Class daoInterface;
+ private Class daoImplementation;
+ private Dao daoInstance;
+ private Dao proxy;
+
+ public StandardDaoManager getDaoManager() {
+ return daoManager;
+ }
+
+ public void setDaoManager(StandardDaoManager daoManager) {
+ this.daoManager = daoManager;
+ }
+
+ public DaoContext getDaoContext() {
+ return daoContext;
+ }
+
+ public void setDaoContext(DaoContext daoContext) {
+ this.daoContext = daoContext;
+ }
+
+ public Class getDaoInterface() {
+ return daoInterface;
+ }
+
+ public void setDaoInterface(Class daoInterface) {
+ this.daoInterface = daoInterface;
+ }
+
+ public Class getDaoImplementation() {
+ return daoImplementation;
+ }
+
+ public void setDaoImplementation(Class daoImplementation) {
+ this.daoImplementation = daoImplementation;
+ }
+
+ public Dao getDaoInstance() {
+ return daoInstance;
+ }
+
+ public void setDaoInstance(Dao daoInstance) {
+ this.daoInstance = daoInstance;
+ }
+
+ public Dao getProxy() {
+ return proxy;
+ }
+
+ public void initProxy() {
+ proxy = DaoProxy.newInstance(this);
+ }
+
+}
Added: ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/impl/DaoProxy.java
URL: http://svn.apache.org/viewvc/ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/impl/DaoProxy.java?rev=683745&view=auto
==============================================================================
--- ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/impl/DaoProxy.java (added)
+++ ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/impl/DaoProxy.java Thu Aug 7 16:21:46 2008
@@ -0,0 +1,73 @@
+package com.ibatis.dao.engine.impl;
+
+import com.ibatis.dao.client.Dao;
+import org.apache.ibatis.reflection.ExceptionUtil;
+
+import java.lang.reflect.*;
+import java.util.*;
+
+public class DaoProxy implements InvocationHandler {
+
+ private static final Set PASSTHROUGH_METHODS = new HashSet();
+
+ private DaoImpl daoImpl;
+
+ static {
+ PASSTHROUGH_METHODS.add("equals");
+ PASSTHROUGH_METHODS.add("getClass");
+ PASSTHROUGH_METHODS.add("hashCode");
+ PASSTHROUGH_METHODS.add("notify");
+ PASSTHROUGH_METHODS.add("notifyAll");
+ PASSTHROUGH_METHODS.add("toString");
+ PASSTHROUGH_METHODS.add("wait");
+ }
+
+ public DaoProxy(DaoImpl daoImpl) {
+ this.daoImpl = daoImpl;
+ }
+
+ public Object invoke(Object proxy, Method method, Object[] args)
+ throws Throwable {
+ Object result = null;
+ if (PASSTHROUGH_METHODS.contains(method.getName())) {
+ try {
+ result = method.invoke(daoImpl.getDaoInstance(), args);
+ } catch (Throwable t) {
+ throw ExceptionUtil.unwrapThrowable(t);
+ }
+ } else {
+ StandardDaoManager daoManager = daoImpl.getDaoManager();
+ DaoContext context = daoImpl.getDaoContext();
+
+ if (daoManager.isExplicitTransaction()) {
+ // Just start the transaction (explicit)
+ try {
+ context.startTransaction();
+ result = method.invoke(daoImpl.getDaoInstance(), args);
+ } catch (Throwable t) {
+ throw ExceptionUtil.unwrapThrowable(t);
+ }
+ } else {
+ // Start, commit and end the transaction (autocommit)
+ try {
+ context.startTransaction();
+ result = method.invoke(daoImpl.getDaoInstance(), args);
+ context.commitTransaction();
+ } catch (Throwable t) {
+ throw ExceptionUtil.unwrapThrowable(t);
+ } finally {
+ context.endTransaction();
+ }
+ }
+
+ }
+ return result;
+ }
+
+ public static Dao newInstance(DaoImpl daoImpl) {
+ return (Dao) Proxy.newProxyInstance(daoImpl.getDaoInterface().getClassLoader(),
+ new Class[]{Dao.class, daoImpl.getDaoInterface()},
+ new DaoProxy(daoImpl));
+ }
+
+}
Added: ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/impl/DaoTransactionState.java
URL: http://svn.apache.org/viewvc/ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/impl/DaoTransactionState.java?rev=683745&view=auto
==============================================================================
--- ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/impl/DaoTransactionState.java (added)
+++ ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/impl/DaoTransactionState.java Thu Aug 7 16:21:46 2008
@@ -0,0 +1,13 @@
+package com.ibatis.dao.engine.impl;
+
+public class DaoTransactionState {
+
+ public static final DaoTransactionState ACTIVE = new DaoTransactionState();
+ public static final DaoTransactionState INACTIVE = new DaoTransactionState();
+ public static final DaoTransactionState COMMITTED = new DaoTransactionState();
+ public static final DaoTransactionState ROLLEDBACK = new DaoTransactionState();
+
+ private DaoTransactionState() {
+ }
+
+}
Added: ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/impl/StandardDaoManager.java
URL: http://svn.apache.org/viewvc/ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/impl/StandardDaoManager.java?rev=683745&view=auto
==============================================================================
--- ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/impl/StandardDaoManager.java (added)
+++ ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/impl/StandardDaoManager.java Thu Aug 7 16:21:46 2008
@@ -0,0 +1,115 @@
+package com.ibatis.dao.engine.impl;
+
+import com.ibatis.dao.client.*;
+
+import java.util.*;
+
+public class StandardDaoManager implements DaoManager {
+
+ private static final String DAO_EXPLICIT_TX = "__DAO_EXPLICIT_TX";
+
+ private ThreadLocal transactionMode = new ThreadLocal();
+ private ThreadLocal contextInTransactionList = new ThreadLocal();
+
+ private Map idContextMap = new HashMap();
+ private Map typeContextMap = new HashMap();
+ private Map daoImplMap = new HashMap();
+
+ public void addContext(DaoContext context) {
+ // Add context ID mapping
+ if (context.getId() != null && context.getId().length() > 0) {
+ if (idContextMap.containsKey(context.getId())) {
+ throw new DaoException("There is already a DAO Context with the ID '" + context.getId() + "'.");
+ }
+ idContextMap.put(context.getId(), context);
+ }
+ // Add type mappings
+ Iterator i = context.getDaoImpls();
+ while (i.hasNext()) {
+ DaoImpl daoImpl = (DaoImpl) i.next();
+
+ // Don't associate a default DAO when multiple DAO impls are registered.
+ if (typeContextMap.containsKey(daoImpl.getDaoInterface())) {
+ typeContextMap.put(daoImpl.getDaoInterface(), null);
+ } else {
+ typeContextMap.put(daoImpl.getDaoInterface(), context);
+ }
+
+ daoImplMap.put(daoImpl.getProxy(), daoImpl);
+ daoImplMap.put(daoImpl.getDaoInstance(), daoImpl);
+ }
+ }
+
+ public Dao getDao(Class iface) {
+ DaoContext context = (DaoContext) typeContextMap.get(iface);
+ if (context == null) {
+ throw new DaoException("There is no DAO implementation found for " + iface + " in any context. If you've " +
+ "registered multiple implementations of this DAO, you must specify the Context ID for the DAO implementation" +
+ "you're looking for using the getDao(Class iface, String contextId) method.");
+ }
+ return context.getDao(iface);
+ }
+
+ public Dao getDao(Class iface, String contextId) {
+ DaoContext context = (DaoContext) idContextMap.get(contextId);
+ if (context == null) {
+ throw new DaoException("There is no Context found with the ID " + contextId + ".");
+ }
+ return context.getDao(iface);
+ }
+
+ public void startTransaction() {
+ transactionMode.set(DAO_EXPLICIT_TX);
+ }
+
+ public void commitTransaction() {
+ List ctxList = getContextInTransactionList();
+ Iterator i = ctxList.iterator();
+ while (i.hasNext()) {
+ DaoContext context = (DaoContext) i.next();
+ context.commitTransaction();
+ }
+ }
+
+ public void endTransaction() {
+ List ctxList = getContextInTransactionList();
+ try {
+ Iterator i = ctxList.iterator();
+ while (i.hasNext()) {
+ DaoContext context = (DaoContext) i.next();
+ context.endTransaction();
+ }
+ } finally {
+ transactionMode.set(null);
+ ctxList.clear();
+ }
+ }
+
+ public DaoTransaction getTransaction(Dao dao) {
+ DaoImpl impl = (DaoImpl) daoImplMap.get(dao);
+ return impl.getDaoContext().getTransaction();
+ }
+
+ public boolean isExplicitTransaction() {
+ return DAO_EXPLICIT_TX.equals(transactionMode.get());
+ }
+
+ public void addContextInTransaction(DaoContext ctx) {
+ List ctxList = getContextInTransactionList();
+ if (!ctxList.contains(ctx)) {
+ ctxList.add(ctx);
+ }
+ }
+
+ private List getContextInTransactionList() {
+ List list = (List) contextInTransactionList.get();
+ if (list == null) {
+ list = new ArrayList();
+ contextInTransactionList.set(list);
+ }
+ return list;
+ }
+
+}
+
+
Added: ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/transaction/ConnectionDaoTransaction.java
URL: http://svn.apache.org/viewvc/ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/transaction/ConnectionDaoTransaction.java?rev=683745&view=auto
==============================================================================
--- ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/transaction/ConnectionDaoTransaction.java (added)
+++ ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/transaction/ConnectionDaoTransaction.java Thu Aug 7 16:21:46 2008
@@ -0,0 +1,11 @@
+package com.ibatis.dao.engine.transaction;
+
+import com.ibatis.dao.client.DaoTransaction;
+
+import java.sql.Connection;
+
+public interface ConnectionDaoTransaction extends DaoTransaction {
+
+ public Connection getConnection();
+
+}
Added: ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/transaction/DaoTransactionManager.java
URL: http://svn.apache.org/viewvc/ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/transaction/DaoTransactionManager.java?rev=683745&view=auto
==============================================================================
--- ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/transaction/DaoTransactionManager.java (added)
+++ ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/transaction/DaoTransactionManager.java Thu Aug 7 16:21:46 2008
@@ -0,0 +1,17 @@
+package com.ibatis.dao.engine.transaction;
+
+import com.ibatis.dao.client.DaoTransaction;
+
+import java.util.Properties;
+
+public interface DaoTransactionManager {
+
+ public void configure(Properties properties);
+
+ public DaoTransaction startTransaction();
+
+ public void commitTransaction(DaoTransaction trans);
+
+ public void rollbackTransaction(DaoTransaction trans);
+
+}
Added: ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/transaction/external/ExternalDaoTransaction.java
URL: http://svn.apache.org/viewvc/ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/transaction/external/ExternalDaoTransaction.java?rev=683745&view=auto
==============================================================================
--- ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/transaction/external/ExternalDaoTransaction.java (added)
+++ ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/transaction/external/ExternalDaoTransaction.java Thu Aug 7 16:21:46 2008
@@ -0,0 +1,15 @@
+package com.ibatis.dao.engine.transaction.external;
+
+import com.ibatis.dao.client.DaoTransaction;
+
+public class ExternalDaoTransaction implements DaoTransaction {
+
+ public void commit() {
+ // Do nothing
+ }
+
+ public void rollback() {
+ // Do nothing
+ }
+
+}
Added: ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/transaction/external/ExternalDaoTransactionManager.java
URL: http://svn.apache.org/viewvc/ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/transaction/external/ExternalDaoTransactionManager.java?rev=683745&view=auto
==============================================================================
--- ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/transaction/external/ExternalDaoTransactionManager.java (added)
+++ ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/transaction/external/ExternalDaoTransactionManager.java Thu Aug 7 16:21:46 2008
@@ -0,0 +1,26 @@
+package com.ibatis.dao.engine.transaction.external;
+
+import com.ibatis.dao.client.DaoTransaction;
+import com.ibatis.dao.engine.transaction.DaoTransactionManager;
+
+import java.util.Properties;
+
+public class ExternalDaoTransactionManager implements DaoTransactionManager {
+
+ public void configure(Properties properties) {
+ // Do nothing
+ }
+
+ public DaoTransaction startTransaction() {
+ return new ExternalDaoTransaction();
+ }
+
+ public void commitTransaction(DaoTransaction trans) {
+ ((ExternalDaoTransaction) trans).commit();
+ }
+
+ public void rollbackTransaction(DaoTransaction trans) {
+ ((ExternalDaoTransaction) trans).rollback();
+ }
+
+}
Added: ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/transaction/jdbc/JdbcDaoTransaction.java
URL: http://svn.apache.org/viewvc/ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/transaction/jdbc/JdbcDaoTransaction.java?rev=683745&view=auto
==============================================================================
--- ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/transaction/jdbc/JdbcDaoTransaction.java (added)
+++ ibatis/trunk/java/ibatis-3/ibatis-3-compat/src/main/java/com/ibatis/dao/engine/transaction/jdbc/JdbcDaoTransaction.java Thu Aug 7 16:21:46 2008
@@ -0,0 +1,63 @@
+package com.ibatis.dao.engine.transaction.jdbc;
+
+import com.ibatis.dao.client.DaoException;
+import com.ibatis.dao.engine.transaction.ConnectionDaoTransaction;
+import org.apache.ibatis.logging.*;
+import org.apache.ibatis.logging.jdbc.ConnectionLogger;
+
+import javax.sql.DataSource;
+import java.sql.*;
+
+public class JdbcDaoTransaction implements ConnectionDaoTransaction {
+
+ private static final Log connectionLog = LogFactory.getLog(Connection.class);
+
+ private Connection connection;
+
+ public JdbcDaoTransaction(DataSource dataSource) {
+ try {
+ connection = dataSource.getConnection();
+ if (connection == null) {
+ throw new DaoException("Could not start transaction. Cause: The DataSource returned a null connection.");
+ }
+ if (connection.getAutoCommit()) {
+ connection.setAutoCommit(false);
+ }
+ if (connectionLog.isDebugEnabled()) {
+ connection = ConnectionLogger.newInstance(connection);
+ }
+ } catch (SQLException e) {
+ throw new DaoException("Error starting JDBC transaction. Cause: " + e);
+ }
+ }
+
+
+ public void commit() {
+ try {
+ try {
+ connection.commit();
+ } finally {
+ connection.close();
+ }
+ } catch (SQLException e) {
+ throw new DaoException("Error committing JDBC transaction. Cause: " + e);
+ }
+ }
+
+ public void rollback() {
+ try {
+ try {
+ connection.rollback();
+ } finally {
+ connection.close();
+ }
+ } catch (SQLException e) {
+ throw new DaoException("Error ending JDBC transaction. Cause: " + e);
+ }
+ }
+
+ public Connection getConnection() {
+ return connection;
+ }
+
+}