View Javadoc

1   /*
2    * Copyright James Leigh (c) 2007.
3    *
4    * Licensed under the Aduna BSD-style license.
5    */
6   package org.openrdf.repository.threadproxy;
7   
8   import org.openrdf.repository.RepositoryConnection;
9   import org.openrdf.repository.RepositoryException;
10  import org.openrdf.repository.base.RepositoryConnectionWrapper;
11  
12  /**
13   * RepositoryConnection that proxies the method calls to a thread local delegate
14   * connection.
15   * 
16   * @author James Leigh
17   * 
18   */
19  public class ThreadProxyRepositoryConnection extends RepositoryConnectionWrapper {
20  
21  	private ThreadLocal<RepositoryConnection> threadContext;
22  
23  	public ThreadProxyRepositoryConnection(ThreadProxyRepository repository) {
24  		super(repository);
25  		threadContext = new ThreadLocal<RepositoryConnection>();
26  	}
27  
28  	@Override
29  	public ThreadProxyRepository getRepository() {
30  		return (ThreadProxyRepository)super.getRepository();
31  	}
32  
33  	@Override
34  	public RepositoryConnection getDelegate()
35  		throws RepositoryException
36  	{
37  		RepositoryConnection conn = threadContext.get();
38  		if (conn == null || !conn.isOpen()) {
39  			conn = getRepository().getDelegate().getConnection();
40  			threadContext.set(conn);
41  		}
42  		return conn;
43  	}
44  
45  	@Override
46  	public void close()
47  		throws RepositoryException
48  	{
49  		RepositoryConnection conn = threadContext.get();
50  		if (conn != null) {
51  			conn.close();
52  			threadContext.set(null);
53  		}
54  	}
55  
56  	@Override
57  	public boolean isAutoCommit()
58  		throws RepositoryException
59  	{
60  		RepositoryConnection conn = threadContext.get();
61  		return conn == null || conn.isAutoCommit();
62  	}
63  
64  	@Override
65  	public boolean isOpen()
66  		throws RepositoryException
67  	{
68  		RepositoryConnection conn = threadContext.get();
69  		return conn != null && conn.isOpen();
70  	}
71  }