/
FBManagedConnection.java
1550 lines (1342 loc) · 61.1 KB
/
FBManagedConnection.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
/*
* Firebird Open Source JavaEE Connector - JDBC Driver
*
* Distributable under LGPL license.
* You may obtain a copy of the License at http://www.gnu.org/copyleft/lgpl.html
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* LGPL License for more details.
*
* This file was created by members of the firebird development team.
* All individual contributions remain the Copyright (C) of those
* individuals. Contributors to this file are either listed here or
* can be obtained from a source control history command.
*
* All rights reserved.
*/
package org.firebirdsql.jaybird.xca;
import org.firebirdsql.gds.*;
import org.firebirdsql.gds.impl.DatabaseParameterBufferExtension;
import org.firebirdsql.gds.impl.DbAttachInfo;
import org.firebirdsql.gds.impl.GDSHelper;
import org.firebirdsql.gds.impl.jni.EmbeddedGDSFactoryPlugin;
import org.firebirdsql.gds.impl.jni.LocalGDSFactoryPlugin;
import org.firebirdsql.gds.ng.*;
import org.firebirdsql.gds.ng.fields.RowValue;
import org.firebirdsql.gds.ng.listeners.DefaultDatabaseListener;
import org.firebirdsql.gds.ng.listeners.DefaultStatementListener;
import org.firebirdsql.gds.ng.listeners.ExceptionListener;
import org.firebirdsql.jdbc.FBConnection;
import org.firebirdsql.jdbc.SQLStateConstants;
import org.firebirdsql.jdbc.Synchronizable;
import org.firebirdsql.jdbc.field.FBField;
import org.firebirdsql.jdbc.field.FieldDataProvider;
import org.firebirdsql.logging.Logger;
import org.firebirdsql.logging.LoggerFactory;
import org.firebirdsql.util.SQLExceptionChainBuilder;
import javax.resource.ResourceException;
import javax.resource.spi.*;
import javax.resource.spi.security.PasswordCredential;
import javax.security.auth.Subject;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import java.io.ByteArrayInputStream;
import java.io.PrintWriter;
import java.net.SocketTimeoutException;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLNonTransientConnectionException;
import java.sql.SQLWarning;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* The class <code>FBManagedConnection</code> implements both the
* ManagedConnection and XAResource interfaces.
*
* @author <a href="mailto:d_jencks@users.sourceforge.net">David Jencks</a>
* @author <a href="mailto:mrotteveel@users.sourceforge.net">Mark Rotteveel</a>
* @version 1.0
*/
public class FBManagedConnection implements ManagedConnection, XAResource, ExceptionListener, Synchronizable {
public static final String WARNING_NO_CHARSET = "WARNING: No connection character set specified (property lc_ctype, encoding, charSet or localEncoding), defaulting to character set ";
public static final String ERROR_NO_CHARSET = "Connection rejected: No connection character set specified (property lc_ctype, encoding, charSet or localEncoding). "
+ "Please specify a connection character set (eg property charSet=utf-8) or consult the Jaybird documentation for more information.";
private static final Logger log = LoggerFactory.getLogger(FBManagedConnection.class);
private final FBManagedConnectionFactory mcf;
private final List<ConnectionEventListener> connectionEventListeners = new CopyOnWriteArrayList<>();
private final List<FBConnection> connectionHandles = Collections.synchronizedList(new ArrayList<FBConnection>());
// This is a bit of hack to be able to get attach warnings into the FBConnection that is created later.
private SQLWarning unnotifiedWarnings;
private int timeout = 0;
private final Map<Xid, FbTransaction> xidMap = new ConcurrentHashMap<>();
private GDSHelper gdsHelper;
private final FbDatabase database;
private final Object syncObject;
private final FBConnectionRequestInfo cri;
private FBTpb tpb;
private int transactionIsolation;
private volatile boolean managedEnvironment = true;
private volatile boolean connectionSharing = true;
private final Set<Xid> preparedXid = Collections.synchronizedSet(new HashSet<Xid>());
private volatile boolean inDistributedTransaction = false;
FBManagedConnection(Subject subject, ConnectionRequestInfo cri, FBManagedConnectionFactory mcf)
throws ResourceException {
this.mcf = mcf;
this.cri = getCombinedConnectionRequestInfo(subject, cri);
this.tpb = mcf.getDefaultTpb();
this.transactionIsolation = mcf.getDefaultTransactionIsolation();
//TODO: XIDs in limbo should be loaded so that XAER_DUPID can be thrown appropriately
try {
DatabaseParameterBuffer dpb = this.cri.getDpb();
if (dpb.getArgumentAsString(DatabaseParameterBuffer.LC_CTYPE) == null
&& dpb.getArgumentAsString(DatabaseParameterBufferExtension.LOCAL_ENCODING) == null) {
String defaultEncoding = getDefaultConnectionEncoding();
if (defaultEncoding == null) {
throw new SQLNonTransientConnectionException(ERROR_NO_CHARSET,
SQLStateConstants.SQL_STATE_CONNECTION_ERROR) ;
}
dpb.addArgument(DatabaseParameterBuffer.LC_CTYPE, defaultEncoding);
String warningMessage = WARNING_NO_CHARSET + defaultEncoding;
log.warn(warningMessage);
notifyWarning(new SQLWarning(warningMessage));
}
if (!dpb.hasArgument(DatabaseParameterBuffer.CONNECT_TIMEOUT) && DriverManager.getLoginTimeout() > 0) {
dpb.addArgument(DatabaseParameterBuffer.CONNECT_TIMEOUT, DriverManager.getLoginTimeout());
}
final FbConnectionProperties connectionProperties = new FbConnectionProperties();
connectionProperties.fromDpb(dpb);
// TODO Move this logic to the GDSType or database factory?
final String gdsTypeName = mcf.getGDSType().toString();
if (!(EmbeddedGDSFactoryPlugin.EMBEDDED_TYPE_NAME.equals(gdsTypeName)
|| LocalGDSFactoryPlugin.LOCAL_TYPE_NAME.equals(gdsTypeName))) {
final DbAttachInfo dbAttachInfo = DbAttachInfo.parseConnectString(mcf.getDatabase());
connectionProperties.setServerName(dbAttachInfo.getServer());
connectionProperties.setPortNumber(dbAttachInfo.getPort());
connectionProperties.setDatabaseName(dbAttachInfo.getFileName());
} else {
connectionProperties.setDatabaseName(mcf.getDatabase());
}
database = mcf.getDatabaseFactory().connect(connectionProperties);
database.addDatabaseListener(new MCDatabaseListener());
database.addExceptionListener(this);
database.attach();
syncObject = database.getSynchronizationObject();
gdsHelper = new GDSHelper(database);
} catch(SQLException ex) {
throw new FBResourceException(ex);
}
}
@Override
public void errorOccurred(Object source, SQLException ex) {
log.trace(ex.getMessage());
if (!FatalGDSErrorHelper.isFatal(ex))
return;
ConnectionEvent event = new ConnectionEvent(FBManagedConnection.this, ConnectionEvent.CONNECTION_ERROR_OCCURRED,
ex);
FBManagedConnection.this.notify(connectionErrorOccurredNotifier, event);
}
private FBConnectionRequestInfo getCombinedConnectionRequestInfo(Subject subject, ConnectionRequestInfo cri)
throws ResourceException {
if (cri == null) {
cri = mcf.getDefaultConnectionRequestInfo();
}
try {
FBConnectionRequestInfo fbcri = (FBConnectionRequestInfo) cri;
if (subject != null) {
// see connector spec, section 8.2.6, contract for
// ManagedConnectionFactory, option A.
for (Object cred : subject.getPrivateCredentials()) {
if (cred instanceof PasswordCredential
&& mcf.equals(((PasswordCredential) cred)
.getManagedConnectionFactory())) {
PasswordCredential pcred = (PasswordCredential) cred;
String user = pcred.getUserName();
String password = new String(pcred.getPassword());
fbcri.setPassword(password);
fbcri.setUserName(user);
break;
}
}
}
return fbcri;
} catch (ClassCastException cce) {
throw new FBResourceException("Incorrect ConnectionRequestInfo class supplied");
}
}
/**
* Get instance of {@link GDSHelper} connected with this managed connection.
*
* @return instance of {@link GDSHelper}.
* @throws SQLException If this connection has no GDSHelper
*/
public GDSHelper getGDSHelper() throws SQLException {
if (gdsHelper == null)
// TODO Right error code?
throw new FbExceptionBuilder().exception(ISCConstants.isc_req_no_trans).toSQLException();
return gdsHelper;
}
public String getDatabase() {
return mcf.getDatabase();
}
public boolean isManagedEnvironment() {
return managedEnvironment;
}
public boolean inTransaction() {
return gdsHelper != null && gdsHelper.inTransaction();
}
public void setManagedEnvironment(boolean managedEnvironment) throws ResourceException{
this.managedEnvironment = managedEnvironment;
// if connection sharing is not enabled, notify currently associated
// connection handle about the state change.
if (!connectionSharing) {
synchronized (connectionHandles) {
if (connectionHandles.size() > 1)
throw new javax.resource.spi.IllegalStateException(
"Multiple connections associated with this managed " +
"connection in non-sharing mode.");
// there will be at most one connection.
for (FBConnection connection : connectionHandles) {
try {
connection.setManagedEnvironment(managedEnvironment);
} catch (SQLException ex) {
throw new FBResourceException(ex);
}
}
}
}
}
/**
* Check if connection sharing is enabled. When connection sharing is
* enabled, multiple connection handles ({@link FBConnection} instances)
* can access this managed connection in thread-safe manner (they synchronize
* on this instance). This feature can be enabled only in JCA environment,
* any other environment must not use connection sharing.
*
* @return <code>true</code> if connection sharing is enabled.
*/
public boolean isConnectionSharing() {
return connectionSharing;
}
/**
* Enable or disable connection sharing. See {@link #isConnectionSharing()}
* method for details.
*
* @param connectionSharing <code>true</code> if connection sharing must be
* enabled.
* @throws ResourceException If connection sharing state cannot be changed
*/
public void setConnectionSharing(boolean connectionSharing) throws ResourceException {
if (!connectionHandles.isEmpty())
throw new javax.resource.spi.IllegalStateException(
"Cannot change connection sharing with active connection handles.");
this.connectionSharing = connectionSharing;
}
/**
* Returns a <code>javax.resource.spi.LocalTransaction</code> instance.
* The LocalTransaction interface is used by the container to manage local
* transactions for a RM instance.
*
* @return LocalTransaction instance
* @throws ResourceException
* generic exception if operation fails
* @throws javax.resource.NotSupportedException
* if the operation is not supported
* @throws ResourceAdapterInternalException
* resource adapter internal error condition
*/
public LocalTransaction getLocalTransaction() {
return new FBLocalTransaction(this, null);
}
/**
* Gets the metadata information for this connection's underlying EIS
* resource manager instance. The ManagedConnectionMetaData interface
* provides information about the underlying EIS instance associated with
* the ManagedConenction instance.
*
* @return ManagedConnectionMetaData instance
* @throws ResourceException
* generic exception if operation fails
* @throws javax.resource.NotSupportedException
* if the operation is not supported
*/
public ManagedConnectionMetaData getMetaData() throws ResourceException {
return new FBManagedConnectionMetaData(this);
}
/**
* Sets the log writer for this ManagedConnection instance.
* <P>
* The log writer is a character output stream to which all logging and
* tracing messages for this ManagedConnection instance will be printed.
* Application Server manages the association of output stream with the
* ManagedConnection instance based on the connection pooling requirements.
* <P>
* When a ManagedConnection object is initially created, the default log
* writer associated with this instance is obtained from the
* <code>ManagedConnectionFactory</code>. An application server can set a
* log writer specific to this ManagedConnection to log/trace this instance
* using setLogWriter method.
*
* @param out
* Character Output stream to be associated
* @throws ResourceException
* generic exception if operation fails
* @throws ResourceAdapterInternalException
* resource adapter related error condition
*/
public void setLogWriter(PrintWriter out) {
// ignore, we are using alternative logging
}
/**
* Gets the log writer for this ManagedConnection instance.
* <P>
* The log writer is a character output stream to which all logging and
* tracing messages for this ManagedConnection instance will be printed.
* <code>ConnectionManager</code> manages the association of output stream
* with the <code>ManagedConnection</code> instance based on the
* connection pooling requirements.
* <P>
* The Log writer associated with a <code>ManagedConnection</code>
* instance can be one set as default from the ManagedConnectionFactory
* (that created this connection) or one set specifically for this instance
* by the application server.
*
* @return Character ourput stream associated with this
* <code>ManagedConnection</code>
* @throws ResourceException
* generic exception if operation fails
*/
public PrintWriter getLogWriter() {
return null;// we are using alternative logging
}
/**
* Add an <code>ConnectionEventListener</code> listener. The listener will
* be notified when a <code>ConnectionEvent</code> occurs.
*
* @param listener
* The <code>ConnectionEventListener</code> to be added
*/
public void addConnectionEventListener(ConnectionEventListener listener) {
connectionEventListeners.add(listener);
}
/**
* Remove a <code>ConnectionEventListner</code> from the listing of
* listeners that will be notified for a <code>ConnectionEvent</code>.
*
* @param listener
* The <code>ConnectionEventListener</code> to be removed
*/
public void removeConnectionEventListener(ConnectionEventListener listener) {
connectionEventListeners.remove(listener);
}
/**
* Used by the container to change the association of an application-level
* connection handle with a ManagedConneciton instance. The container should
* find the right ManagedConnection instance and call the
* associateConnection method.
* <P>
* The resource adapter is required to implement the associateConnection
* method. The method implementation for a ManagedConnection should
* dissociate the connection handle (passed as a parameter) from its
* currently associated ManagedConnection and associate the new connection
* handle with itself.
*
* @param connection
* Application-level connection handle
* @throws ResourceException
* Failed to associate the connection handle with this
* ManagedConnection instance
* @throws javax.resource.spi.IllegalStateException
* Illegal state for invoking this method
* @throws ResourceAdapterInternalException
* Resource adapter internal error condition
*/
public void associateConnection(Object connection) throws ResourceException {
if (!connectionSharing)
disassociateConnections();
try {
final FBConnection abstractConnection = (FBConnection) connection;
abstractConnection.setManagedConnection(this);
connectionHandles.add(abstractConnection);
} catch (ClassCastException cce) {
throw new FBResourceException("invalid connection supplied to associateConnection.", cce);
}
}
/**
* Application server calls this method to force any cleanup on the
* <code>ManagedConnection</code> instance.
* <P>
* The method {@link ManagedConnection#cleanup}initiates a cleanup of the
* any client-specific state as maintained by a ManagedConnection instance.
* The cleanup should invalidate all connection handles that had been
* created using this <code>ManagedConnection</code> instance. Any attempt
* by an application component to use the connection handle after cleanup of
* the underlying <code>ManagedConnection</code> should result in an
* exception.
* <P>
* The cleanup of ManagedConnection is always driven by an application
* server. An application server should not invoke
* {@link ManagedConnection#cleanup}when there is an uncompleted
* transaction (associated with a ManagedConnection instance) in progress.
* <P>
* The invocation of {@link ManagedConnection#cleanup}method on an already
* cleaned-up connection should not throw an exception.
*
* The cleanup of <code>ManagedConnection</code> instance resets its
* client specific state and prepares the connection to be put back in to a
* connection pool. The cleanup method should not cause resource adapter to
* close the physical pipe and reclaim system resources associated with the
* physical connection.
*
* @throws ResourceException
* generic exception if operation fails
* @throws ResourceAdapterInternalException
* resource adapter internal error condition
* @throws javax.resource.spi.IllegalStateException
* Illegal state for calling connection cleanup. Example - if a
* local transaction is in progress that doesn't allow
* connection cleanup
*/
public void cleanup() throws ResourceException {
disassociateConnections();
try {
getGDSHelper().setCurrentTransaction(null);
} catch (SQLException e) {
throw new FBResourceException(e);
}
// reset the TPB from the previous transaction.
this.tpb = mcf.getDefaultTpb();
this.transactionIsolation = mcf.getDefaultTransactionIsolation();
}
/**
* Disassociate connections from current managed connection.
*/
private void disassociateConnections() throws ResourceException {
SQLExceptionChainBuilder<SQLException> chain = new SQLExceptionChainBuilder<>();
synchronized (connectionHandles) {
// Iterate over copy of list as connection.close() will remove connection
List<FBConnection> connectionHandleCopy = new ArrayList<>(connectionHandles);
for (FBConnection connection : connectionHandleCopy) {
try {
connection.close();
} catch (SQLException sqlex) {
chain.append(sqlex);
}
}
}
if (chain.hasException())
throw new FBResourceException(chain.getException());
}
/**
* Disassociate connections without cleanly closing them.
*/
private void forceDisassociateConnections() {
synchronized (connectionHandles) {
Iterator<FBConnection> connectionIterator = connectionHandles.iterator();
while (connectionIterator.hasNext()) {
FBConnection connection = connectionIterator.next();
connection.setManagedConnection(null);
try {
connection.close();
} catch (SQLException sqlex) {
log.debug("Exception ignored during forced disassociation", sqlex);
}
connectionIterator.remove();
}
}
}
/**
* Creates a new connection handle for the underlying physical connection
* represented by the <code>ManagedConnection</code> instance. This
* connection handle is used by the application code to refer to the
* underlying physical connection. A connection handle is tied to its
* <code>ManagedConnection</code> instance in a resource adapter
* implementation specific way.
* <P>
*
* The <code>ManagedConnection</code> uses the Subject and additional
* <code>ConnectionRequestInfo</code> (which is specific to resource
* adapter and opaque to application server) to set the state of the
* physical connection.
*
* @param subject
* security context as JAAS subject
* @param cri
* ConnectionRequestInfo instance
* @return generic <code>Object</code> instance representing the
* connection handle. For CCI, the connection handle created by a
* <code>ManagedConnection</code> instance is of the type
* <code>javax.resource.cci.Connection</code>.
* @throws ResourceException
* generic exception if operation fails
* @throws ResourceAdapterInternalException
* resource adapter internal error condition
* @throws javax.resource.spi.SecurityException
* security related error condition
* @throws CommException
* failed communication with EIS instance
* @throws EISSystemException
* internal error condition in EIS instance - used if EIS
* instance is involved in setting state of
* <code>ManagedConnection</code>
*/
public Object getConnection(Subject subject, ConnectionRequestInfo cri)
throws ResourceException {
if (!matches(subject, cri))
throw new FBResourceException("Incompatible subject or ConnectionRequestInfo in getConnection!");
if (!connectionSharing)
disassociateConnections();
FBConnection c = mcf.newConnection(this);
try {
if (unnotifiedWarnings != null) {
c.addWarning(unnotifiedWarnings);
unnotifiedWarnings = null;
}
c.setManagedEnvironment(isManagedEnvironment());
connectionHandles.add(c);
return c;
} catch(SQLException ex) {
throw new FBResourceException(ex);
}
}
/**
* Destroys the physical connection to the underlying resource manager. To
* manage the size of the connection pool, an application server can
* explictly call {@link ManagedConnection#destroy}to destroy a physical
* connection. A resource adapter should destroy all allocated system
* resources for this <code>ManagedConnection</code> instance when the
* method destroy is called.
*
* @throws ResourceException
* generic exception if operation failed
* @throws javax.resource.spi.IllegalStateException
* illegal state for destroying connection
*/
public void destroy() throws ResourceException {
destroy(null);
}
public void destroy(ConnectionEvent connectionEvent) throws ResourceException {
if (gdsHelper == null)
return;
try {
if (isBrokenConnection(connectionEvent)) {
FbDatabase currentDatabase = gdsHelper.getCurrentDatabase();
currentDatabase.forceClose();
} else {
if (inTransaction())
throw new javax.resource.spi.IllegalStateException(
"Can't destroy managed connection with active transaction");
gdsHelper.detachDatabase();
}
} catch (SQLException ge) {
throw new FBResourceException("Can't detach from db.", ge);
} finally {
gdsHelper = null;
forceDisassociateConnections();
}
}
private boolean isBrokenConnection(ConnectionEvent connectionEvent) {
if (connectionEvent == null || connectionEvent.getId() != ConnectionEvent.CONNECTION_ERROR_OCCURRED) {
return false;
}
Exception connectionEventException = connectionEvent.getException();
if (connectionEventException == null) {
return false;
}
SQLException firstSqlException = findException(connectionEventException, SQLException.class);
if (firstSqlException != null && isBrokenConnectionErrorCode(firstSqlException.getErrorCode())) {
return true;
}
if (findException(connectionEventException, SocketTimeoutException.class) != null) {
return true;
}
//noinspection RedundantIfStatement
if (findException(connectionEventException, SocketTimeoutException.class) != null) {
return true;
}
return false;
}
private boolean isBrokenConnectionErrorCode(int iscCode) {
return iscCode == ISCConstants.isc_network_error
|| iscCode == ISCConstants.isc_net_read_err
|| iscCode == ISCConstants.isc_net_write_err;
}
private <T extends Exception> T findException(Exception root, Class<T> exceptionType) {
Throwable current = root;
while (current != null) {
if (exceptionType.isInstance(current)) {
return exceptionType.cast(current);
}
current = current.getCause();
}
return null;
}
/**
* Return an XA resource to the caller.
* <P>
* In both <code>javax.sql.XAConnection</code> and
* <code>javax.resource.spi.MangagedConnection</code>.
*
* @return the XAResource
*/
public XAResource getXAResource() {
log.debug("XAResource requested from FBManagedConnection");
return this;
}
// --------------------------------------------------------------
// XAResource implementation
// --------------------------------------------------------------
// TODO validate correctness of state set
private static final Set<TransactionState> XID_ACTIVE_STATE = Collections.unmodifiableSet(EnumSet.of(TransactionState.ACTIVE, TransactionState.PREPARED, TransactionState.PREPARING));
boolean isXidActive(Xid xid) {
FbTransaction transaction = xidMap.get(xid);
return transaction != null && XID_ACTIVE_STATE.contains(transaction.getState());
}
/**
* Commits a transaction.
*
* @throws XAException
* Occurs when the state was not correct (end never called), the
* transaction ID is wrong, the connection was set to
* Auto-Commit, or the commit on the underlying connection
* fails. The error code differs depending on the exact
* situation.
*/
public void commit(Xid id, boolean onePhase) throws XAException {
try {
mcf.notifyCommit(this, id, onePhase);
} catch (GDSException ge) {
throw new XAException(ge.getXAErrorCode());
}
}
/**
* The <code>internalCommit</code> method performs the requested commit
* and may throw a GDSException to be interpreted by the caller.
*
* @param xid
* a <code>Xid</code> value
* @param onePhase
* a <code>boolean</code> value
* @exception XAException
* if an error occurs
*/
void internalCommit(Xid xid, boolean onePhase) throws XAException {
if (log.isTraceEnabled()) log.trace("Commit called: " + xid);
FbTransaction committingTr = xidMap.get(xid);
// check that prepare has NOT been called when onePhase = true
if (onePhase && isPrepared(xid))
throw new FBXAException("Cannot commit one-phase when transaction has been prepared", XAException.XAER_PROTO);
// check that prepare has been called when onePhase = false
if (!onePhase && !isPrepared(xid))
throw new FBXAException("Cannot commit two-phase when transaction has not been prepared", XAException.XAER_PROTO);
if (committingTr == null)
throw new FBXAException("Commit called with unknown transaction", XAException.XAER_NOTA);
try {
if (committingTr == getGDSHelper().getCurrentTransaction())
throw new FBXAException("Commit called with non-ended xid", XAException.XAER_PROTO);
committingTr.commit();
} catch (SQLException ge) {
if (gdsHelper != null) {
try {
committingTr.rollback();
} catch (SQLException ge2) {
log.debug("Exception rolling back failed tx: ", ge2);
}
} else {
log.warn("Unable to rollback failed tx, connection closed or lost");
}
throw new FBXAException(ge.getMessage(), XAException.XAER_RMERR, ge);
} finally {
xidMap.remove(xid);
preparedXid.remove(xid);
}
}
private boolean isPrepared(Xid xid) {
return preparedXid.contains(xid);
}
/**
* Dissociates a resource from a global transaction.
*
* @throws XAException
* Occurs when the state was not correct (end called twice), or
* the transaction ID is wrong.
*/
public void end(Xid id, int flags) throws XAException {
if (flags != XAResource.TMSUCCESS && flags != XAResource.TMFAIL && flags != XAResource.TMSUSPEND)
throw new FBXAException("flag not allowed in this context: " + flags + ", valid flags are TMSUCCESS, TMFAIL, TMSUSPEND", XAException.XAER_PROTO);
try {
internalEnd(id, flags);
} catch (SQLException e) {
throw new FBXAException(XAException.XAER_RMERR, e);
}
mcf.notifyEnd(this, id);
inDistributedTransaction = false;
try {
// This will reset the managed environment of the associated connections and set the transaction coordinator to local
// TODO This is a bit of a hack; need to find a better way; this doesn't work with connectionSharing = true
setManagedEnvironment(isManagedEnvironment());
} catch (ResourceException ex) {
throw new FBXAException("Reset of managed state failed", XAException.XAER_RMERR, ex);
}
}
/**
* The <code>internalEnd</code> method ends the xid as requested if
* appropriate and throws a GDSException including the appropriate XA error
* code and a message if not. The caller can decode the exception as
* necessary.
*
* @param xid
* a <code>Xid</code> value
* @param flags
* an <code>int</code> value
* @exception XAException
* if an error occurs
*/
void internalEnd(Xid xid, int flags) throws XAException, SQLException {
if (log.isDebugEnabled()) log.debug("End called: " + xid);
FbTransaction endingTr = xidMap.get(xid);
if (endingTr == null)
throw new FBXAException("Unrecognized transaction", XAException.XAER_NOTA);
if (flags == XAResource.TMFAIL) {
try {
endingTr.rollback();
getGDSHelper().setCurrentTransaction(null);
} catch (SQLException ex) {
throw new FBXAException("can't rollback transaction", XAException.XAER_RMFAIL, ex);
}
}
else if (flags == XAResource.TMSUCCESS) {
if (gdsHelper != null && endingTr == gdsHelper.getCurrentTransaction())
gdsHelper.setCurrentTransaction(null);
else
throw new FBXAException("You are trying to end a transaction that is not the current transaction",
XAException.XAER_INVAL);
}
else if (flags == XAResource.TMSUSPEND) {
if (gdsHelper != null && endingTr == gdsHelper.getCurrentTransaction())
gdsHelper.setCurrentTransaction(null);
else
throw new FBXAException("You are trying to suspend a transaction that is not the current transaction",
XAException.XAER_INVAL);
}
}
private final static String FORGET_FIND_QUERY = "SELECT RDB$TRANSACTION_ID, RDB$TRANSACTION_DESCRIPTION "
+ "FROM RDB$TRANSACTIONS WHERE RDB$TRANSACTION_STATE IN (2, 3)";
private final static String FORGET_DELETE_QUERY = "DELETE FROM RDB$TRANSACTIONS WHERE RDB$TRANSACTION_ID = ";
/**
* Indicates that no further action will be taken on behalf of this
* transaction (after a heuristic failure). It is assumed this will be
* called after a failed commit or rollback.
*
* @throws XAException
* Occurs when the state was not correct (end never called), or
* the transaction ID is wrong.
*/
public void forget(Xid id) throws XAException {
long inLimboId = -1;
try {
// find XID
// TODO: Is there a reason why this piece of code can't use the JDBC Statement class?
FbTransaction trHandle2 = database.startTransaction(tpb.getTransactionParameterBuffer());
FbStatement stmtHandle2 = database.createStatement(trHandle2);
GDSHelper gdsHelper2 = new GDSHelper(database);
gdsHelper2.setCurrentTransaction(trHandle2);
stmtHandle2.prepare(FORGET_FIND_QUERY);
DataProvider dataProvider0 = new DataProvider(0);
stmtHandle2.addStatementListener(dataProvider0);
DataProvider dataProvider1 = new DataProvider(1);
stmtHandle2.addStatementListener(dataProvider1);
stmtHandle2.execute(RowValue.EMPTY_ROW_VALUE);
stmtHandle2.fetchRows(10);
FBField field0 = FBField.createField(stmtHandle2.getRowDescriptor().getFieldDescriptor(0), dataProvider0, gdsHelper2, false);
FBField field1 = FBField.createField(stmtHandle2.getRowDescriptor().getFieldDescriptor(1), dataProvider1, gdsHelper2, false);
int row = 0;
while(row < dataProvider0.getRowCount()) {
dataProvider0.setRow(row);
dataProvider1.setRow(row);
long inLimboTxId = field0.getLong();
byte[] inLimboMessage = field1.getBytes();
try {
FBXid xid = new FBXid(new ByteArrayInputStream(inLimboMessage), inLimboTxId);
boolean gtridEquals = Arrays.equals(xid.getGlobalTransactionId(), id.getGlobalTransactionId());
boolean bqualEquals = Arrays.equals(xid.getBranchQualifier(), id.getBranchQualifier());
if (gtridEquals && bqualEquals) {
inLimboId = inLimboTxId;
break;
}
} catch(FBIncorrectXidException ex) {
String message = "incorrect XID format in RDB$TRANSACTIONS where RDB$TRANSACTION_ID=" + inLimboTxId;
log.warn(message + ": " + ex + "; see debug level for stacktrace");
log.debug(message, ex);
}
row++;
}
stmtHandle2.close();
trHandle2.commit();
} catch (SQLException | ResourceException ex) {
log.debug("can't perform query to fetch xids", ex);
throw new FBXAException(XAException.XAER_RMFAIL, ex);
}
if (inLimboId == -1)
throw new FBXAException("XID not found", XAException.XAER_NOTA); // TODO: is XAER_NOTA the proper error code ?
try {
// delete XID
FbTransaction trHandle2 = database.startTransaction(tpb.getTransactionParameterBuffer());
FbStatement stmtHandle2 = database.createStatement(trHandle2);
stmtHandle2.prepare(FORGET_DELETE_QUERY + inLimboId);
stmtHandle2.execute(RowValue.EMPTY_ROW_VALUE);
stmtHandle2.close();
trHandle2.commit();
} catch (SQLException ex) {
throw new FBXAException("can't perform query to fetch xids", XAException.XAER_RMFAIL, ex);
}
}
/**
* Gets the transaction timeout.
*/
public int getTransactionTimeout() throws javax.transaction.xa.XAException {
return timeout;
}
/**
* Retrieve whether this <code>FBManagedConnection</code> uses the same
* ResourceManager as <code>res</code>. This method relies on
* <code>res</code> being a Firebird implementation of
* <code>XAResource</code>.
*
* @param res
* The other <code>XAResource</code> to compare to
* @return <code>true</code> if <code>res</code> uses the same
* ResourceManager, <code>false</code> otherwise
*/
public boolean isSameRM(XAResource res) throws XAException {
return res instanceof FBManagedConnection
&& database == ((FBManagedConnection) res).database;
}
/**
* Prepares a transaction to commit.
*
* @throws XAException
* Occurs when the state was not correct (end never called), the
* transaction ID is wrong, or the connection was set to
* Auto-Commit.
*/
public int prepare(Xid xid) throws javax.transaction.xa.XAException {
try {
return mcf.notifyPrepare(this, xid);
} catch (GDSException ge) {
throw new FBXAException(XAException.XAER_RMERR, ge);
}
}
int internalPrepare(Xid xid) throws FBXAException {
if (log.isTraceEnabled()) log.trace("prepare called: " + xid);
FbTransaction committingTr = xidMap.get(xid);
if (committingTr == null)
throw new FBXAException("Prepare called with unknown transaction", XAException.XAER_NOTA);
try {
if (committingTr == getGDSHelper().getCurrentTransaction())
throw new FBXAException("Prepare called with non-ended xid", XAException.XAER_PROTO);
FBXid fbxid;
if (xid instanceof FBXid) {
fbxid = (FBXid) xid;
} else {
fbxid = new FBXid(xid);
}
byte[] message = fbxid.toBytes();
committingTr.prepare(message);
} catch (SQLException ge) {
try {
if (gdsHelper != null) {
committingTr.rollback();
} else {
log.warn("Unable to rollback failed tx, connection closed or lost");
}
} catch (SQLException ge2) {
log.debug("Exception rolling back failed tx: ", ge2);
} finally {
xidMap.remove(xid);
}
log.warn("error in prepare", ge);
throw new FBXAException(XAException.XAER_RMERR, ge);
}
preparedXid.add(xid);
return XA_OK;
}
private static final String RECOVERY_QUERY =
"SELECT RDB$TRANSACTION_ID, RDB$TRANSACTION_DESCRIPTION "
+ "FROM RDB$TRANSACTIONS";
/**
* Obtain a list of prepared transaction branches from a resource manager.
* The transaction manager calls this method during recovery to obtain the
* list of transaction branches that are currently in prepared or
* heuristically completed states.
*
* @param flags
* One of TMSTARTRSCAN, TMENDRSCAN, TMNOFLAGS. TMNOFLAGS must be
* used when no other flags are set in flags.
* @return The resource manager returns zero or more XIDs for the
* transaction branches that are currently in a prepared or
* heuristically completed state. If an error occurs during the
* operation, the resource manager should throw the appropriate
* XAException.