forked from vratsel/generic-jms-ra
/
JmsManagedConnection.java
1010 lines (911 loc) · 37.4 KB
/
JmsManagedConnection.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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright The WildFly Authors
* SPDX-License-Identifier: Apache-2.0
*/
package org.jboss.resource.adapter.jms;
import org.jboss.resource.adapter.jms.util.SecurityActions;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.TimeUnit;
import jakarta.jms.Connection;
import jakarta.jms.ConnectionFactory;
import jakarta.jms.ExceptionListener;
import jakarta.jms.JMSContext;
import jakarta.jms.JMSException;
import jakarta.jms.QueueConnection;
import jakarta.jms.QueueConnectionFactory;
import jakarta.jms.ResourceAllocationException;
import jakarta.jms.Session;
import jakarta.jms.TopicConnection;
import jakarta.jms.TopicConnectionFactory;
import jakarta.jms.XAConnection;
import jakarta.jms.XAConnectionFactory;
import jakarta.jms.XAJMSContext;
import jakarta.jms.XAQueueConnection;
import jakarta.jms.XAQueueConnectionFactory;
import jakarta.jms.XAQueueSession;
import jakarta.jms.XASession;
import jakarta.jms.XATopicConnection;
import jakarta.jms.XATopicConnectionFactory;
import jakarta.jms.XATopicSession;
import javax.naming.Context;
import javax.naming.NamingException;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ConnectionEvent;
import jakarta.resource.spi.ConnectionEventListener;
import jakarta.resource.spi.ConnectionRequestInfo;
import jakarta.resource.spi.IllegalStateException;
import jakarta.resource.spi.LocalTransaction;
import jakarta.resource.spi.ManagedConnection;
import jakarta.resource.spi.ManagedConnectionMetaData;
import jakarta.resource.spi.SecurityException;
import javax.security.auth.Subject;
import javax.transaction.xa.XAResource;
import org.jboss.logging.Logger;
import org.jboss.resource.adapter.jms.inflow.JmsActivation;
/**
* <p>
* Managed Connection, manages one or more JMS sessions.
* <p/>
* <p>
* Every ManagedConnection will have a physical JMSConnection under the hood.
* This may leave out several session, as specifyed in 5.5.4 Multiple Connection
* Handles. Thread safe semantics is provided
* <p/>
* <p>
* Hm. If we are to follow the example in 6.11 this will not work. We would have
* to use the SAME session. This means we will have to guard against concurrent
* access. We use a stack, and only allowes the handle at the top of the stack
* to do things.
* <p/>
* <p>
* As to transactions we some fairly hairy alternatives to handle: XA - we get
* an XA. We may now only do transaction through the XAResource, since a
* XASession MUST throw exceptions in commit etc. But since XA support implies
* LocatTransaction support, we will have to use the XAResource in the
* LocalTransaction class. LocalTx - we get a normal session. The
* LocalTransaction will then work against the normal session api.
* <p/>
* <p>
* An invokation of JMS MAY BE DONE in none transacted context. What do we do
* then? How much should we leave to the user???
* <p/>
* <p>
* One possible solution is to use transactions any way, but under the hood. If
* not LocalTransaction or XA has been aquired by the container, we have to do
* the commit in send and publish. (CHECK is the container required to get a XA
* every time it uses a managed connection? No its is not, only at creation!)
* <p/>
* <p>
* Does this mean that a session one time may be used in a transacted env, and
* another time in a not transacted.
* <p/>
* <p>
* Maybe we could have this simple rule:
* <p/>
* <p>
* If a user is going to use non trans:
* <ul>
* <li>mark that i ra deployment descr
* <li>Use a JmsProviderAdapter with non XA factorys
* <li>Mark session as non transacted (this defeats the purpose of specifying
* <li>trans attrinbutes in deploy descr NOT GOOD
* </ul>
* <p/>
* <p>
* From the JMS tutorial: "When you create a session in an enterprise bean, the
* container ignores the arguments you specify, because it manages all
* transactional properties for enterprise beans."
* <p/>
* <p>
* And further: "You do not specify a message acknowledgment mode when you
* create a message-driven bean that uses container-managed transactions. The
* container handles acknowledgment automatically."
* <p/>
* <p>
* On Session or Connection:
* <p>
* From Tutorial: "A JMS API resource is a JMS API connection or a JMS API
* session." But in the J2EE spec only connection is considered a resource.
* <p/>
* <p>
* Not resolved: connectionErrorOccurred: it is verry hard to know from the
* exceptions thrown if it is a connection error. Should we register an
* ExceptionListener and mark al handles as errounous? And then let them send
* the event and throw an exception?
*
* @author <a href="mailto:peter.antman@tim.se">Peter Antman</a>.
* @author <a href="mailto:jason@planet57.com">Jason Dillon</a>
* @author <a href="mailto:adrian@jboss.com">Adrian Brock</a>
*/
public class JmsManagedConnection implements ManagedConnection, ExceptionListener {
private static final Logger log = Logger.getLogger(JmsManagedConnection.class);
private JmsManagedConnectionFactory mcf;
private JmsConnectionRequestInfo info;
private String user;
private String pwd;
private volatile boolean isSetUp;
private volatile boolean isDestroyed;
private ReentrantLock lock = new ReentrantLock(true);
// Physical JMS connection stuff
private Connection con = null;
private Session session = null;
private XASession xaSession = null;
private XAResource xaResource = null;
private boolean xaTransacted = false;
private JMSContext context = null;
private XAJMSContext xaContext = null;
/**
* Holds all current JmsSession handles.
*/
private Set<JmsSession> handles = Collections.synchronizedSet(new HashSet<>());
/**
* The event listeners
*/
private Vector<ConnectionEventListener> listeners = new Vector<>();
/**
* Create a <tt>JmsManagedConnection</tt>.
*
* @param mcf
* @param info
* @param user
* @param pwd
* @throws ResourceException
*/
public JmsManagedConnection(final JmsManagedConnectionFactory mcf,
final ConnectionRequestInfo info,
final String user,
final String pwd)
throws ResourceException {
this.mcf = mcf;
// seem like its asking for trouble here
this.info = (JmsConnectionRequestInfo) info;
this.user = user;
this.pwd = pwd;
try {
setup();
} catch (Throwable t) {
try {
destroy();
} catch (Throwable ignored) {
}
if (t instanceof ResourceException) {
throw (ResourceException) t;
} else {
throw new ResourceException(t);
}
}
}
//---- ManagedConnection API ----
/**
* Get the physical connection handler. This bummer will be called in two
* situations:
* <ol>
* <li>When a new mc has bean created and a connection is needed
* <li>When an mc has been fetched from the pool (returned in match*)
* </ol>
* It may also be called multiple time without a cleanup, to support
* connection sharing.
*
* @param subject
* @param info
* @return A new connection object.
* @throws ResourceException
*/
@Override
public Object getConnection(final Subject subject, final ConnectionRequestInfo info) throws ResourceException {
// Check user first
JmsCred cred = JmsCred.getJmsCred(mcf, subject, info);
// Null users are allowed!
if (user != null && !user.equals(cred.name)) {
throw new SecurityException("Password credentials not the same, reauthentication not allowed");
}
if (cred.name != null && user == null) {
throw new SecurityException("Password credentials not the same, reauthentication not allowed");
}
user = cred.name; // Basically meaningless
if (isDestroyed) {
throw new IllegalStateException("ManagedConnection already destroyed");
}
// Create a handle
JmsSession handle = new JmsSession(this, (JmsConnectionRequestInfo) info);
handles.add(handle);
return handle;
}
/**
* Destroy all handles.
*
* @throws ResourceException Failed to close one or more handles.
*/
private void destroyHandles() throws ResourceException {
try {
if (con != null) {
con.stop();
}
} catch (Throwable t) {
log.trace("Ignored error stopping connection", t);
}
Iterator<JmsSession> iter = handles.iterator();
while (iter.hasNext()) {
iter.next().destroy();
}
// clear the handles map
handles.clear();
}
/**
* Destroy the physical connection.
*
* @throws ResourceException Could not property close the session and
* connection.
*/
@Override
public final void destroy() throws ResourceException {
if (isDestroyed || con == null) {
return;
}
synchronized (this) {
if (isDestroyed || con == null) {
return;
}
try {
con.setExceptionListener(null);
} catch (JMSException e) {
log.debug("Error unsetting the exception listener " + this, e);
}
destroyHandles();
try {
if (xaTransacted && xaContext != null) {
xaContext.close();
}
if (context != null) {
context.close();
}
// Close session and connection
try {
if (session != null) {
session.close();
}
} catch (JMSException e) {
log.debug("Error closing session " + this, e);
}
try {
if (xaTransacted && xaSession != null) {
xaSession.close();
}
} catch (JMSException e) {
log.debug("Error closing xaSession " + this, e);
}
con.close();
} catch (Throwable e) {
throw new ResourceException("Could not properly close the session and connection", e);
} finally {
isDestroyed = true;
}
}
}
/**
* Cleans up, from the spec - The cleanup of ManagedConnection instance
* resets its client specific state. Does that mean that authentication
* should be redone.
*
* FIXME
*
* @throws jakarta.resource.ResourceException
*/
@Override
public void cleanup() throws ResourceException {
if (isDestroyed) {
throw new IllegalStateException("ManagedConnection already destroyed");
}
// destory handles
destroyHandles();
boolean isActive = false;
if (lock.hasQueuedThreads()) {
Collection<Thread> threads = lock.getQueuedThreads();
for (Thread thread : threads) {
Throwable t = new Throwable("Thread waiting for lock during cleanup");
t.setStackTrace(thread.getStackTrace());
log.warn(t.getMessage(), t);
}
isActive = true;
}
if (lock.isLocked()) {
Throwable t = new Throwable("Lock owned during cleanup");
t.setStackTrace(lock.getOwner().getStackTrace());
log.warn(t.getMessage(), t);
isActive = true;
}
if (isActive) {
// There are active lock - make sure that the JCA container kills
// this handle by throwing an exception
throw new ResourceException("Still active locks for " + this);
}
}
/**
* Move a handler from one mc to this one.
*
* @param obj An object of type JmsSession.
* @throws ResourceException Failed to associate connection.
* @throws IllegalStateException ManagedConnection in an illegal state.
*/
@Override
public void associateConnection(final Object obj) throws ResourceException {
//
// Should we check auth, ie user and pwd? FIXME
//
if (!isDestroyed && obj instanceof JmsSession) {
JmsSession h = (JmsSession) obj;
h.setManagedConnection(this);
handles.add(h);
} else {
throw new IllegalStateException("ManagedConnection in an illegal state");
}
}
protected void lock() {
lock.lock();
}
protected void tryLock() throws JMSException {
int tryLock = mcf.getUseTryLock();
if (tryLock <= 0) {
lock();
return;
}
try {
if (lock.tryLock(tryLock, TimeUnit.SECONDS) == false) {
throw new ResourceAllocationException("Unable to obtain lock in " + tryLock + " seconds: " + this);
}
} catch (InterruptedException e) {
throw new ResourceAllocationException("Interrupted attempting lock: " + this);
}
}
protected void unlock() {
if (lock.isLocked()) {
lock.unlock();
} else {
log.warn("Owner is null");
Throwable t = new Throwable("Thread trying to unlock");
t.setStackTrace(Thread.currentThread().getStackTrace());
log.warn(t.getMessage(), t);
}
}
/**
* Add a connection event listener.
*
* @param l The connection event listener to be added.
*/
@Override
public void addConnectionEventListener(final ConnectionEventListener l) {
listeners.addElement(l);
if (log.isTraceEnabled()) {
log.trace("ConnectionEvent listener added: " + l);
}
}
/**
* Remove a connection event listener.
*
* @param l The connection event listener to be removed.
*/
@Override
public void removeConnectionEventListener(final ConnectionEventListener l) {
listeners.removeElement(l);
}
/**
* Get the XAResource for the connection.
*
* @return The XAResource for the connection.
* @throws ResourceException XA transaction not supported
*/
@Override
public XAResource getXAResource() throws ResourceException {
//
// Spec says a mc must always return the same XA resource,
// so we cache it.
//
if (!xaTransacted) {
return null;
}
if (xaResource == null) {
xaResource = xaSession.getXAResource();
}
if (log.isTraceEnabled()) {
log.trace("XAResource=" + xaResource);
}
xaResource = new JmsXAResource(this, xaResource);
return xaResource;
}
/**
* Get the location transaction for the connection.
*
* @return The local transaction for the connection.
* @throws ResourceException
*/
@Override
public LocalTransaction getLocalTransaction() throws ResourceException {
LocalTransaction tx = new JmsLocalTransaction(this);
if (log.isTraceEnabled()) {
log.trace("LocalTransaction=" + tx);
}
return tx;
}
/**
* Get the meta data for the connection.
*
* @return The meta data for the connection.
* @throws ResourceException
* @throws IllegalStateException ManagedConnection already destroyed.
*/
@Override
public ManagedConnectionMetaData getMetaData() throws ResourceException {
if (isDestroyed) {
throw new IllegalStateException("ManagedConnection already destroyd");
}
return new JmsMetaData(this);
}
/**
* Set the log writer for this connection.
*
* @param out The log writer for this connection.
* @throws ResourceException
*/
@Override
public void setLogWriter(final PrintWriter out) throws ResourceException {
//
// jason: screw the logWriter stuff for now it sucks ass
//
}
/**
* Get the log writer for this connection.
*
* @return Always null
* @throws jakarta.resource.ResourceException
*/
@Override
public PrintWriter getLogWriter() throws ResourceException {
//
// jason: screw the logWriter stuff for now it sucks ass
//
return null;
}
// --- Exception listener implementation
@Override
public void onException(JMSException exception) {
if (isDestroyed) {
if (log.isTraceEnabled()) {
log.trace("Ignoring error on already destroyed connection " + this, exception);
}
return;
}
log.warn("Handling jms exception failure: " + this, exception);
// We need to unlock() before sending the connection error to the
// event listeners. Otherwise the lock won't be in sync once
// cleanup() is called
if (lock.isLocked() && Thread.currentThread().equals(lock.getOwner())) {
unlock();
}
try {
con.setExceptionListener(null);
} catch (JMSException e) {
log.debug("Unable to unset exception listener", e);
}
ConnectionEvent event = new ConnectionEvent(this, ConnectionEvent.CONNECTION_ERROR_OCCURRED, exception);
sendEvent(event);
}
// --- Api to JmsSession
/**
* Get the session for this connection.
*
* @return Either a topic or queue connection.
*/
protected Session getSession() {
return session;
}
/**
* Get the JMSContext for this connection.
* @return the JMSContext for this connection.
*/
protected JMSContext getJMSContext() {
return context;
}
/**
* Send an event.
*
* @param event The event to send.
*/
protected void sendEvent(final ConnectionEvent event) {
int type = event.getId();
if (log.isTraceEnabled()) {
log.trace("Sending connection event: " + type);
}
// convert to an array to avoid concurrent modification exceptions
ConnectionEventListener[] list
= listeners.toArray(new ConnectionEventListener[listeners.size()]);
for (int i = 0; i < list.length; i++) {
switch (type) {
case ConnectionEvent.CONNECTION_CLOSED:
list[i].connectionClosed(event);
break;
case ConnectionEvent.LOCAL_TRANSACTION_STARTED:
list[i].localTransactionStarted(event);
break;
case ConnectionEvent.LOCAL_TRANSACTION_COMMITTED:
list[i].localTransactionCommitted(event);
break;
case ConnectionEvent.LOCAL_TRANSACTION_ROLLEDBACK:
list[i].localTransactionRolledback(event);
break;
case ConnectionEvent.CONNECTION_ERROR_OCCURRED:
list[i].connectionErrorOccurred(event);
break;
default:
throw new IllegalArgumentException("Illegal eventType: " + type);
}
}
}
/**
* Remove a handle from the handle map.
*
* @param handle The handle to remove.
*/
protected void removeHandle(final JmsSession handle) {
handles.remove(handle);
}
// --- Used by MCF
/**
* Get the request info for this connection.
*
* @return The request info for this connection.
*/
protected ConnectionRequestInfo getInfo() {
return info;
}
/**
* Get the connection factory for this connection.
*
* @return The connection factory for this connection.
*/
protected JmsManagedConnectionFactory getManagedConnectionFactory() {
return mcf;
}
void start() throws JMSException {
con.start();
}
void stop() throws JMSException {
con.stop();
}
// --- Used by MetaData
/**
* Get the user name for this connection.
*
* @return The user name for this connection.
*/
protected String getUserName() {
return user;
}
/**
* Setup the connection.
*
* @throws ResourceException
*/
private void setup() throws ResourceException {
synchronized (this) {
if (isSetUp) {
return;
}
boolean trace = log.isTraceEnabled();
ClassLoader oldTCCL = SecurityActions.getThreadContextClassLoader();
try {
SecurityActions.setThreadContextClassLoader(JmsManagedConnection.class.getClassLoader());
Context jndiContext = JmsActivation.convertStringToContext(mcf.getJndiParameters());
Object factory;
boolean transacted = info.isTransacted();
int ack = transacted ? Session.SESSION_TRANSACTED : info.getAcknowledgeMode();
String connectionFactory = mcf.getConnectionFactory();
if (connectionFactory == null) {
throw new IllegalStateException("No configured 'connectionFactory'.");
}
factory = jndiContext.lookup(connectionFactory);
con = createConnection(factory, user, pwd, transacted, ack);
if (con instanceof XAConnection && transacted) {
switch (mcf.getProperties().getType()) {
case JmsConnectionFactory.QUEUE:
xaSession = ((XAQueueConnection) con).createXAQueueSession();
session = ((XAQueueSession) xaSession).getQueueSession();
break;
case JmsConnectionFactory.TOPIC:
xaSession = ((XATopicConnection) con).createXATopicSession();
session = ((XATopicSession) xaSession).getTopicSession();
break;
default:
xaSession = ((XAConnection) con).createXASession();
session = xaSession.getSession();
break;
}
xaTransacted = true;
} else {
switch (mcf.getProperties().getType()) {
case JmsConnectionFactory.QUEUE:
session = ((QueueConnection) con).createQueueSession(transacted, ack);
break;
case JmsConnectionFactory.TOPIC:
session = ((TopicConnection) con).createTopicSession(transacted, ack);
break;
default:
session = con.createSession(transacted, ack);
break;
}
if (trace) {
log.trace("Using a non-XA Connection. "
+ "It will not be able to participate in a Global UOW");
}
}
con.setExceptionListener(this);
if (trace) {
log.trace("created connection: " + con);
}
log.debug("xaSession=" + xaSession + ", Session=" + session);
log.debug("transacted=" + transacted + ", ack=" + ack);
isSetUp = true;
} catch (NamingException | JMSException e) {
throw new ResourceException("Unable to setup connection", e);
} finally {
SecurityActions.setThreadContextClassLoader(oldTCCL);
}
}
}
/**
* Create a connection from the given factory.An XA connection will be
* created if possible.
*
* @param factory An object that implements ConnectionFactory,
* XAQConnectionFactory
* @param username The username to use or null for no user.
* @param password The password for the given username or null if no
* username was specified.
* @param transacted
* @param ack
* @return A connection.
* @throws JMSException Failed to create connection.
* @throws IllegalArgumentException Factory is null or invalid.
*/
public Connection createConnection(final Object factory, final String username, final String password, boolean transacted, int ack)
throws JMSException {
if (factory == null) {
throw new IllegalArgumentException("factory is null");
}
log.debug("using connection factory: " + factory);
log.debug("using username/password: " + String.valueOf(username) + "/-- not shown --");
Connection connection = null;
if (factory instanceof XAConnectionFactory) {
XAConnectionFactory xaConnFactory = (XAConnectionFactory) factory;
if (username != null) {
switch (mcf.getProperties().getType()) {
case JmsConnectionFactory.QUEUE: {
Connection realConnection = ((XAQueueConnectionFactory) xaConnFactory).createXAQueueConnection(username, password);
context = null;
connection = new JmsConnectionSession(realConnection, createSession(realConnection, transacted, ack));
break;
}
case JmsConnectionFactory.TOPIC: {
Connection realConnection = ((XATopicConnectionFactory) xaConnFactory).createXATopicConnection(username, password);
context = null;
connection = new JmsConnectionSession(realConnection, createSession(realConnection, transacted, ack));
break;
}
case JmsConnectionFactory.AGNOSTIC: {
Connection realConnection = xaConnFactory.createXAConnection(username, password);
if (isJMS_2_0(xaConnFactory)) {
xaContext = xaConnFactory.createXAContext(username, password);
context = xaContext.getContext();
} else {
context = null;
xaContext = null;
}
connection = new JmsConnectionSession(realConnection, createSession(realConnection, transacted, ack));
break;
}
case JmsConnectionFactory.JMS_CONTEXT:
try {
xaContext = xaConnFactory.createXAContext(username, password);
// Attempt to set the client id
if (info.getClientID() != null && !info.getClientID().equals(xaContext.getClientID())) {
xaContext.setClientID(info.getClientID());
}
context = xaContext.getContext();
connection = new JmsConnectionContext(context);
} catch (Exception e) {
log.fatal("The JMS provider does not support the JMS 2.0 XAJMSContext interface: "
+ e.getMessage(), e);
throw new JMSException("The JMS provider does not support the JMS 2.0 XAJMSContext interface");
}
break;
}
} else {
switch (mcf.getProperties().getType()) {
case JmsConnectionFactory.QUEUE: {
Connection realConnection = ((XAQueueConnectionFactory) xaConnFactory).createXAQueueConnection();
context = null;
connection = new JmsConnectionSession(realConnection, createSession(realConnection, transacted, ack));
break;
}
case JmsConnectionFactory.TOPIC: {
Connection realConnection = ((XATopicConnectionFactory) xaConnFactory).createXATopicConnection();
context = null;
connection = new JmsConnectionSession(realConnection, createSession(realConnection, transacted, ack));
break;
}
case JmsConnectionFactory.AGNOSTIC: {
Connection realConnection = xaConnFactory.createXAConnection();
if(isJMS_2_0(xaConnFactory)) {
xaContext = xaConnFactory.createXAContext();
context = xaContext.getContext();
} else {
xaContext = null;
context = null;
}
connection = new JmsConnectionSession(realConnection, createSession(realConnection, transacted, ack));
break;
}
case JmsConnectionFactory.JMS_CONTEXT:
try {
xaContext = xaConnFactory.createXAContext();
// Attempt to set the client id
if (info.getClientID() != null && !info.getClientID().equals(xaContext.getClientID())) {
xaContext.setClientID(info.getClientID());
}
context = xaContext.getContext();
connection = new JmsConnectionContext(context);
} catch (Exception e) {
log.fatal("The JMS provider does not support the JMS 2.0 XAJMSContext interface: "
+ e.getMessage(), e);
throw new JMSException("The JMS provider does not support the JMS 2.0 XAJMSContext interface");
}
break;
}
}
log.debug("created XAConnection: " + connection);
} else if (factory instanceof ConnectionFactory) {
ConnectionFactory nonXAConnFactory = (ConnectionFactory) factory;
if (username != null) {
switch (mcf.getProperties().getType()) {
case JmsConnectionFactory.QUEUE: {
Connection realConnection = ((QueueConnectionFactory) nonXAConnFactory).createQueueConnection(username, password);
context = null;
connection = new JmsConnectionSession(realConnection, createSession(realConnection, transacted, ack));
break;
}
case JmsConnectionFactory.TOPIC: {
Connection realConnection = ((TopicConnectionFactory) nonXAConnFactory).createTopicConnection(username, password);
context = null;
connection = new JmsConnectionSession(realConnection, createSession(realConnection, transacted, ack));
break;
}
case JmsConnectionFactory.AGNOSTIC: {
Connection realConnection = nonXAConnFactory.createConnection(username, password);
if(isJMS_2_0(nonXAConnFactory)) {
context = nonXAConnFactory.createContext(username, password);
} else {
context = null;
}
connection = new JmsConnectionSession(realConnection, createSession(realConnection, transacted, ack));
break;
}
case JmsConnectionFactory.JMS_CONTEXT:
try {
context = nonXAConnFactory.createContext(username, password);
// Attempt to set the client id
if (info.getClientID() != null && !info.getClientID().equals(context.getClientID())) {
context.setClientID(info.getClientID());
}
connection = new JmsConnectionContext(context);
} catch (Exception e) {
log.fatal(
"The JMS provider does not support the JMS 2.0 JMSContext interface: " + e.getMessage(),
e);
throw new JMSException("The JMS provider does not support the JMS 2.0 JMSContext interface");
}
break;
}
} else {
switch (mcf.getProperties().getType()) {
case JmsConnectionFactory.QUEUE: {
Connection realConnection = ((QueueConnectionFactory) nonXAConnFactory).createQueueConnection();
context = null;
connection = new JmsConnectionSession(realConnection, createSession(realConnection, transacted, ack));
break;
}
case JmsConnectionFactory.TOPIC: {
Connection realConnection = ((TopicConnectionFactory) nonXAConnFactory).createTopicConnection();
context = null;
connection = new JmsConnectionSession(realConnection, createSession(realConnection, transacted, ack));
break;
}
case JmsConnectionFactory.AGNOSTIC: {
Connection realConnection = nonXAConnFactory.createConnection();
if(isJMS_2_0(nonXAConnFactory)) {
context = nonXAConnFactory.createContext();
} else {
context = null;
}
connection = new JmsConnectionSession(realConnection, createSession(realConnection, transacted, ack));
break;
}
case JmsConnectionFactory.JMS_CONTEXT:
try {
context = nonXAConnFactory.createContext();
// Attempt to set the client id
if (info.getClientID() != null && !info.getClientID().equals(context.getClientID())) {
context.setClientID(info.getClientID());
}
connection = new JmsConnectionContext(context);
} catch (Exception e) {
log.fatal(
"The JMS provider does not support the JMS 2.0 JMSContext interface: " + e.getMessage(),
e);
throw new JMSException("The JMS provider does not support the JMS 2.0 JMSContext interface");
}
break;
}
}
log.debug("created " + mcf.getProperties().getSessionDefaultType() + " connection: " + connection);
} else {
throw new IllegalArgumentException("factory is invalid: " + factory);
}
return connection;
}
private boolean hasMethod(Object object, String method) {
try {
object.getClass().getMethod(method);
} catch (NoSuchMethodException | java.lang.SecurityException ex) {
return false;
}
return true;
}
private Session createSession(Connection connection, boolean xaTransacted, int ack) throws JMSException {
Session internalSession;
// Attempt to set the client id prior to creating a session. The QPID JMS client doesn't allow it after a session is created
if (info.getClientID() != null && !info.getClientID().equals(connection.getClientID())) {
connection.setClientID(info.getClientID());
}
if (isJMS_2_0(connection)) {
internalSession = connection.createSession();
log.debug("Session " + internalSession + " created with createSession()");
} else {
internalSession = connection.createSession(xaTransacted, ack);
log.debug("Session " + internalSession + " created with createSession(" + xaTransacted + ", " + ack + ")");
}
return internalSession;
}
private boolean isJMS_2_0(Connection connection) {
return mcf.isJMS20() && hasMethod(connection, "createSession");
}
private boolean isJMS_2_0(ConnectionFactory connectionFactory) {
return mcf.isJMS20() && hasMethod(connectionFactory, "createContext");
}
private boolean isJMS_2_0(XAConnectionFactory connectionFactory) {
return mcf.isJMS20() && hasMethod(connectionFactory, "createXAContext");
}
@Override
public String toString() {
return "JmsManagedConnection{"
+ "mcf=" + mcf
+ ", info=" + info
+ ", user=" + user
+ ", pwd=****"
+ ", isSetUp=" + isSetUp
+ ", isDestroyed=" + isDestroyed
+ ", lock=" + lock