-
Notifications
You must be signed in to change notification settings - Fork 37.7k
/
WebSphereUowTransactionManager.java
425 lines (374 loc) · 15.3 KB
/
WebSphereUowTransactionManager.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.transaction.jta;
import java.util.List;
import javax.naming.NamingException;
import com.ibm.websphere.uow.UOWSynchronizationRegistry;
import com.ibm.wsspi.uow.UOWAction;
import com.ibm.wsspi.uow.UOWActionException;
import com.ibm.wsspi.uow.UOWException;
import com.ibm.wsspi.uow.UOWManager;
import com.ibm.wsspi.uow.UOWManagerFactory;
import org.springframework.lang.Nullable;
import org.springframework.transaction.IllegalTransactionStateException;
import org.springframework.transaction.InvalidTimeoutException;
import org.springframework.transaction.NestedTransactionNotSupportedException;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionSystemException;
import org.springframework.transaction.support.CallbackPreferringPlatformTransactionManager;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.DefaultTransactionStatus;
import org.springframework.transaction.support.SmartTransactionObject;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.transaction.support.TransactionSynchronizationUtils;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
/**
* WebSphere-specific PlatformTransactionManager implementation that delegates
* to a {@link com.ibm.wsspi.uow.UOWManager} instance, obtained from WebSphere's
* JNDI environment. This allows Spring to leverage the full power of the WebSphere
* transaction coordinator, including transaction suspension, in a manner that is
* perfectly compliant with officially supported WebSphere API.
*
* <p>The {@link CallbackPreferringPlatformTransactionManager} interface
* implemented by this class indicates that callers should preferably pass in
* a {@link TransactionCallback} through the {@link #execute} method, which
* will be handled through the callback-based WebSphere UOWManager API instead
* of through standard JTA API (UserTransaction / TransactionManager). This avoids
* the use of the non-public {@code javax.transaction.TransactionManager}
* API on WebSphere, staying within supported WebSphere API boundaries.
*
* <p>This transaction manager implementation derives from Spring's standard
* {@link JtaTransactionManager}, inheriting the capability to support programmatic
* transaction demarcation via {@code getTransaction} / {@code commit} /
* {@code rollback} calls through a JTA UserTransaction handle, for callers
* that do not use the TransactionCallback-based {@link #execute} method. However,
* transaction suspension is <i>not</i> supported in this {@code getTransaction}
* style (unless you explicitly specify a {@link #setTransactionManager} reference,
* despite the official WebSphere recommendations). Use the {@link #execute} style
* for any code that might require transaction suspension.
*
* <p>This transaction manager is compatible with WebSphere 6.1.0.9 and above.
* The default JNDI location for the UOWManager is "java:comp/websphere/UOWManager".
* If the location happens to differ according to your WebSphere documentation,
* simply specify the actual location through this transaction manager's
* "uowManagerName" bean property.
*
* <p><b>NOTE: This JtaTransactionManager is intended to refine specific transaction
* demarcation behavior on Spring's side. It will happily co-exist with independently
* configured WebSphere transaction strategies in your persistence provider, with no
* need to specifically connect those setups in any way.</b>
*
* @author Juergen Hoeller
* @since 2.5
* @see #setUowManager
* @see #setUowManagerName
* @see com.ibm.wsspi.uow.UOWManager
*/
@SuppressWarnings("serial")
public class WebSphereUowTransactionManager extends JtaTransactionManager
implements CallbackPreferringPlatformTransactionManager {
/**
* Default JNDI location for the WebSphere UOWManager.
* @see #setUowManagerName
*/
public static final String DEFAULT_UOW_MANAGER_NAME = "java:comp/websphere/UOWManager";
@Nullable
private UOWManager uowManager;
@Nullable
private String uowManagerName;
/**
* Create a new WebSphereUowTransactionManager.
*/
public WebSphereUowTransactionManager() {
setAutodetectTransactionManager(false);
}
/**
* Create a new WebSphereUowTransactionManager for the given UOWManager.
* @param uowManager the WebSphere UOWManager to use as direct reference
*/
public WebSphereUowTransactionManager(UOWManager uowManager) {
this();
this.uowManager = uowManager;
}
/**
* Set the WebSphere UOWManager to use as direct reference.
* <p>Typically just used for test setups; in a Java EE environment,
* the UOWManager will always be fetched from JNDI.
* @see #setUserTransactionName
*/
public void setUowManager(UOWManager uowManager) {
this.uowManager = uowManager;
}
/**
* Set the JNDI name of the WebSphere UOWManager.
* The default "java:comp/websphere/UOWManager" is used if not set.
* @see #DEFAULT_USER_TRANSACTION_NAME
* @see #setUowManager
*/
public void setUowManagerName(String uowManagerName) {
this.uowManagerName = uowManagerName;
}
@Override
public void afterPropertiesSet() throws TransactionSystemException {
initUserTransactionAndTransactionManager();
// Fetch UOWManager handle from JNDI, if necessary.
if (this.uowManager == null) {
if (this.uowManagerName != null) {
this.uowManager = lookupUowManager(this.uowManagerName);
}
else {
this.uowManager = lookupDefaultUowManager();
}
}
}
/**
* Look up the WebSphere UOWManager in JNDI via the configured name.
* @param uowManagerName the JNDI name of the UOWManager
* @return the UOWManager object
* @throws TransactionSystemException if the JNDI lookup failed
* @see #setJndiTemplate
* @see #setUowManagerName
*/
protected UOWManager lookupUowManager(String uowManagerName) throws TransactionSystemException {
try {
if (logger.isDebugEnabled()) {
logger.debug("Retrieving WebSphere UOWManager from JNDI location [" + uowManagerName + "]");
}
return getJndiTemplate().lookup(uowManagerName, UOWManager.class);
}
catch (NamingException ex) {
throw new TransactionSystemException(
"WebSphere UOWManager is not available at JNDI location [" + uowManagerName + "]", ex);
}
}
/**
* Obtain the WebSphere UOWManager from the default JNDI location
* "java:comp/websphere/UOWManager".
* @return the UOWManager object
* @throws TransactionSystemException if the JNDI lookup failed
* @see #setJndiTemplate
*/
protected UOWManager lookupDefaultUowManager() throws TransactionSystemException {
try {
logger.debug("Retrieving WebSphere UOWManager from default JNDI location [" + DEFAULT_UOW_MANAGER_NAME + "]");
return getJndiTemplate().lookup(DEFAULT_UOW_MANAGER_NAME, UOWManager.class);
}
catch (NamingException ex) {
logger.debug("WebSphere UOWManager is not available at default JNDI location [" +
DEFAULT_UOW_MANAGER_NAME + "] - falling back to UOWManagerFactory lookup");
return UOWManagerFactory.getUOWManager();
}
}
private UOWManager obtainUOWManager() {
Assert.state(this.uowManager != null, "No UOWManager set");
return this.uowManager;
}
/**
* Registers the synchronizations as interposed JTA Synchronization on the UOWManager.
*/
@Override
protected void doRegisterAfterCompletionWithJtaTransaction(
JtaTransactionObject txObject, List<TransactionSynchronization> synchronizations) {
obtainUOWManager().registerInterposedSynchronization(new JtaAfterCompletionSynchronization(synchronizations));
}
/**
* Returns {@code true} since WebSphere ResourceAdapters (as exposed in JNDI)
* implicitly perform transaction enlistment if the MessageEndpointFactory's
* {@code isDeliveryTransacted} method returns {@code true}.
* In that case we'll simply skip the {@link #createTransaction} call.
* @see javax.resource.spi.endpoint.MessageEndpointFactory#isDeliveryTransacted
* @see org.springframework.jca.endpoint.AbstractMessageEndpointFactory
* @see TransactionFactory#createTransaction
*/
@Override
public boolean supportsResourceAdapterManagedTransactions() {
return true;
}
@Override
@Nullable
public <T> T execute(@Nullable TransactionDefinition definition, TransactionCallback<T> callback)
throws TransactionException {
if (definition == null) {
// Use defaults if no transaction definition given.
definition = new DefaultTransactionDefinition();
}
if (definition.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {
throw new InvalidTimeoutException("Invalid transaction timeout", definition.getTimeout());
}
UOWManager uowManager = obtainUOWManager();
int pb = definition.getPropagationBehavior();
boolean existingTx = (uowManager.getUOWStatus() != UOWSynchronizationRegistry.UOW_STATUS_NONE &&
uowManager.getUOWType() != UOWSynchronizationRegistry.UOW_TYPE_LOCAL_TRANSACTION);
int uowType = UOWSynchronizationRegistry.UOW_TYPE_GLOBAL_TRANSACTION;
boolean joinTx = false;
boolean newSynch = false;
if (existingTx) {
if (pb == TransactionDefinition.PROPAGATION_NEVER) {
throw new IllegalTransactionStateException(
"Transaction propagation 'never' but existing transaction found");
}
if (pb == TransactionDefinition.PROPAGATION_NESTED) {
throw new NestedTransactionNotSupportedException(
"Transaction propagation 'nested' not supported for WebSphere UOW transactions");
}
if (pb == TransactionDefinition.PROPAGATION_SUPPORTS ||
pb == TransactionDefinition.PROPAGATION_REQUIRED ||
pb == TransactionDefinition.PROPAGATION_MANDATORY) {
joinTx = true;
newSynch = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
}
else if (pb == TransactionDefinition.PROPAGATION_NOT_SUPPORTED) {
uowType = UOWSynchronizationRegistry.UOW_TYPE_LOCAL_TRANSACTION;
newSynch = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
}
else {
newSynch = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
}
}
else {
if (pb == TransactionDefinition.PROPAGATION_MANDATORY) {
throw new IllegalTransactionStateException(
"Transaction propagation 'mandatory' but no existing transaction found");
}
if (pb == TransactionDefinition.PROPAGATION_SUPPORTS ||
pb == TransactionDefinition.PROPAGATION_NOT_SUPPORTED ||
pb == TransactionDefinition.PROPAGATION_NEVER) {
uowType = UOWSynchronizationRegistry.UOW_TYPE_LOCAL_TRANSACTION;
newSynch = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
}
else {
newSynch = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
}
}
boolean debug = logger.isDebugEnabled();
if (debug) {
logger.debug("Creating new transaction with name [" + definition.getName() + "]: " + definition);
}
SuspendedResourcesHolder suspendedResources = (!joinTx ? suspend(null) : null);
UOWActionAdapter<T> action = null;
try {
boolean actualTransaction = (uowType == UOWManager.UOW_TYPE_GLOBAL_TRANSACTION);
if (actualTransaction && definition.getTimeout() > TransactionDefinition.TIMEOUT_DEFAULT) {
uowManager.setUOWTimeout(uowType, definition.getTimeout());
}
if (debug) {
logger.debug("Invoking WebSphere UOW action: type=" + uowType + ", join=" + joinTx);
}
action = new UOWActionAdapter<>(definition, callback, actualTransaction, !joinTx, newSynch, debug);
uowManager.runUnderUOW(uowType, joinTx, action);
if (debug) {
logger.debug("Returned from WebSphere UOW action: type=" + uowType + ", join=" + joinTx);
}
return action.getResult();
}
catch (UOWException | UOWActionException ex) {
TransactionSystemException tse =
new TransactionSystemException("UOWManager transaction processing failed", ex);
Throwable appEx = action.getException();
if (appEx != null) {
logger.error("Application exception overridden by rollback exception", appEx);
tse.initApplicationException(appEx);
}
throw tse;
}
finally {
if (suspendedResources != null) {
resume(null, suspendedResources);
}
}
}
/**
* Adapter that executes the given Spring transaction within the WebSphere UOWAction shape.
*/
private class UOWActionAdapter<T> implements UOWAction, SmartTransactionObject {
private final TransactionDefinition definition;
private final TransactionCallback<T> callback;
private final boolean actualTransaction;
private final boolean newTransaction;
private final boolean newSynchronization;
private boolean debug;
@Nullable
private T result;
@Nullable
private Throwable exception;
public UOWActionAdapter(TransactionDefinition definition, TransactionCallback<T> callback,
boolean actualTransaction, boolean newTransaction, boolean newSynchronization, boolean debug) {
this.definition = definition;
this.callback = callback;
this.actualTransaction = actualTransaction;
this.newTransaction = newTransaction;
this.newSynchronization = newSynchronization;
this.debug = debug;
}
@Override
public void run() {
UOWManager uowManager = obtainUOWManager();
DefaultTransactionStatus status = prepareTransactionStatus(
this.definition, (this.actualTransaction ? this : null),
this.newTransaction, this.newSynchronization, this.debug, null);
try {
this.result = this.callback.doInTransaction(status);
triggerBeforeCommit(status);
}
catch (Throwable ex) {
this.exception = ex;
if (status.isDebug()) {
logger.debug("Rolling back on application exception from transaction callback", ex);
}
uowManager.setRollbackOnly();
}
finally {
if (status.isLocalRollbackOnly()) {
if (status.isDebug()) {
logger.debug("Transaction callback has explicitly requested rollback");
}
uowManager.setRollbackOnly();
}
triggerBeforeCompletion(status);
if (status.isNewSynchronization()) {
List<TransactionSynchronization> synchronizations = TransactionSynchronizationManager.getSynchronizations();
TransactionSynchronizationManager.clear();
if (!synchronizations.isEmpty()) {
uowManager.registerInterposedSynchronization(new JtaAfterCompletionSynchronization(synchronizations));
}
}
}
}
@Nullable
public T getResult() {
if (this.exception != null) {
ReflectionUtils.rethrowRuntimeException(this.exception);
}
return this.result;
}
@Nullable
public Throwable getException() {
return this.exception;
}
@Override
public boolean isRollbackOnly() {
return obtainUOWManager().getRollbackOnly();
}
@Override
public void flush() {
TransactionSynchronizationUtils.triggerFlush();
}
}
}