1
22
23 package com.liferay.portal.dao.jdbc.aop;
24
25 import com.liferay.portal.kernel.log.Log;
26 import com.liferay.portal.kernel.log.LogFactoryUtil;
27
28 import java.util.Stack;
29
30 import javax.sql.DataSource;
31
32 import org.springframework.aop.TargetSource;
33
34
41 public class DynamicDataSourceTargetSource implements TargetSource {
42
43 public Stack<String> getMethodStack() {
44 Stack<String> methodStack = _methodStackThreadLocal.get();
45
46 if (methodStack == null) {
47 methodStack = new Stack<String>();
48
49 _methodStackThreadLocal.set(methodStack);
50 }
51
52 return methodStack;
53 }
54
55 public Operation getOperation() {
56 Operation operation = _operationTypeThreadLocal.get();
57
58 if (operation == null) {
59 operation = Operation.WRITE;
60
61 _operationTypeThreadLocal.set(operation);
62 }
63
64 return operation;
65 }
66
67 public Object getTarget() throws Exception {
68 Operation operationType = getOperation();
69
70 if (operationType == Operation.READ) {
71 if (_log.isTraceEnabled()) {
72 _log.trace("Returning read data source");
73 }
74
75 return _readDataSource;
76 }
77 else {
78 if (_log.isTraceEnabled()) {
79 _log.trace("Returning write data source");
80 }
81
82 return _writeDataSource;
83 }
84 }
85
86 public Class<DataSource> getTargetClass() {
87 return DataSource.class;
88 }
89
90 public boolean isStatic() {
91 return false;
92 }
93
94 public String popMethod() {
95 Stack<String> methodStack = getMethodStack();
96
97 String method = methodStack.pop();
98
99 setOperation(Operation.WRITE);
100
101 return method;
102 }
103
104 public void pushMethod(String method) {
105 Stack<String> methodStack = getMethodStack();
106
107 methodStack.push(method);
108 }
109
110 public void releaseTarget(Object target) throws Exception {
111 }
112
113 public void setOperation(Operation operation) {
114 if (_log.isDebugEnabled()) {
115 _log.debug("Method stack " + getMethodStack());
116 }
117
118 if (!inOperation()) {
119 _operationTypeThreadLocal.set(operation);
120 }
121 }
122
123 public void setReadDataSource(DataSource readDataSource) {
124 _readDataSource = readDataSource;
125 }
126
127 public void setWriteDataSource(DataSource writeDataSource) {
128 _writeDataSource = writeDataSource;
129 }
130
131 protected boolean inOperation() {
132 Stack<String> methodStack = getMethodStack();
133
134 return !methodStack.empty();
135 }
136
137 private static Log _log =
138 LogFactoryUtil.getLog(DynamicDataSourceTargetSource.class);
139
140 private static ThreadLocal<Stack<String>> _methodStackThreadLocal =
141 new ThreadLocal<Stack<String>>();
142 private static ThreadLocal<Operation> _operationTypeThreadLocal =
143 new ThreadLocal<Operation>();
144
145 private DataSource _readDataSource;
146 private DataSource _writeDataSource;
147
148 }