001/* 002 * (C) Copyright 2014 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Stephane Lacoin 018 */ 019package org.nuxeo.ecm.core.storage.sql.jdbc; 020 021import java.lang.reflect.InvocationHandler; 022import java.lang.reflect.InvocationTargetException; 023import java.lang.reflect.Method; 024import java.lang.reflect.Proxy; 025 026import javax.transaction.Transaction; 027 028import org.nuxeo.ecm.core.storage.sql.Mapper; 029import org.nuxeo.runtime.transaction.TransactionHelper; 030 031public class JDBCMapperTxSuspender implements InvocationHandler { 032 033 protected final Mapper mapper; 034 035 protected JDBCMapperTxSuspender(Mapper mapper) { 036 this.mapper = mapper; 037 } 038 039 protected Object doInvoke(Method method, Object[] args) throws Throwable { 040 try { 041 return method.invoke(mapper, args); 042 } catch (InvocationTargetException cause) { 043 throw cause.getTargetException(); 044 } 045 } 046 047 @Override 048 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 049 Transaction tx = TransactionHelper.suspendTransaction(); 050 try { 051 return doInvoke(method, args); 052 } finally { 053 if (tx != null) { 054 TransactionHelper.resumeTransaction(tx); 055 } 056 } 057 } 058 059 public static Mapper newConnector(Mapper mapper) { 060 return (Mapper) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), 061 new Class<?>[] { Mapper.class }, new JDBCMapperTxSuspender(mapper)); 062 } 063}