1 28 29 package com.caucho.jstl.rt; 30 31 import com.caucho.log.Log; 32 import com.caucho.util.L10N; 33 34 import javax.servlet.jsp.JspException ; 35 import javax.servlet.jsp.JspTagException ; 36 import javax.servlet.jsp.tagext.TagSupport ; 37 import javax.servlet.jsp.tagext.TryCatchFinally ; 38 import javax.sql.DataSource ; 39 import java.sql.Connection ; 40 import java.sql.SQLException ; 41 import java.util.logging.Level ; 42 import java.util.logging.Logger ; 43 44 public class SqlTransactionTag extends TagSupport implements TryCatchFinally { 45 private static final Logger log = Log.open(SqlTransactionTag.class); 46 private static final L10N L = new L10N(SqlTransactionTag.class); 47 48 private Object _dataSource; 49 private String _isolation; 50 51 private Connection _conn; 52 private int _oldIsolation; 53 54 57 public void setDataSource(Object dataSource) 58 { 59 _dataSource = dataSource; 60 } 61 62 65 public void setIsolation(String isolation) 66 { 67 _isolation = isolation; 68 } 69 70 public int doStartTag() throws JspException 71 { 72 if (pageContext.getAttribute("caucho.jstl.sql.conn") != null) 73 throw new JspTagException (L.l("nexted sql:transaction are forbidden")); 74 75 try { 76 DataSource ds; 77 78 ds = SqlQueryTag.getDataSource(pageContext, _dataSource); 79 80 int isolationCode = -1; 81 if (_isolation == null) { 82 } 83 else if (_isolation.equals("read_committed")) 84 isolationCode = Connection.TRANSACTION_READ_COMMITTED; 85 else if (_isolation.equals("read_uncommitted")) 86 isolationCode = Connection.TRANSACTION_READ_UNCOMMITTED; 87 else if (_isolation.equals("repeatable_read")) 88 isolationCode = Connection.TRANSACTION_REPEATABLE_READ; 89 else if (_isolation.equals("serializable")) 90 isolationCode = Connection.TRANSACTION_SERIALIZABLE; 91 else 92 throw new JspTagException (L.l("unknown sql:transaction isolation ~{0}'", _isolation)); 93 94 _conn = ds.getConnection(); 95 96 _oldIsolation = _conn.getTransactionIsolation(); 97 98 _conn.setAutoCommit(false); 99 100 if (_isolation != null && isolationCode != _oldIsolation) 101 _conn.setTransactionIsolation(isolationCode); 102 103 pageContext.setAttribute("caucho.jstl.sql.conn", _conn); 104 } catch (JspException e) { 105 throw e; 106 } catch (Exception e) { 107 throw new JspException (e); 108 } 109 110 return EVAL_PAGE; 111 } 112 113 public void doCatch(Throwable t) throws Throwable 114 { 115 if (_conn != null) 116 _conn.rollback(); 117 118 throw t; 119 } 120 121 public void doFinally() 122 { 123 try { 124 pageContext.removeAttribute("caucho.jstl.sql.conn"); 125 126 if (_conn != null) { 127 Connection conn = _conn; 128 _conn = null; 129 130 try { 131 conn.commit(); 132 } finally { 133 try { 134 conn.setTransactionIsolation(_oldIsolation); 135 } catch (SQLException e) { 136 } 137 138 try { 139 conn.close(); 140 } catch (SQLException e) { 141 } 142 } 143 } 144 } catch (Exception e) { 145 log.log(Level.FINE, e.toString(), e); 146 } 147 } 148 } 149 | Popular Tags |