/
ConnectionFactoryImpl.java
908 lines (852 loc) · 34.5 KB
/
ConnectionFactoryImpl.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
/**********************************************************************
Copyright (c) 2007 Erik Bengtson and others. All rights reserved.
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
http://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.
Contributors:
...
**********************************************************************/
package org.datanucleus.store.rdbms;
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.util.HashMap;
import java.util.Map;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import javax.sql.XAConnection;
import javax.sql.XADataSource;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import org.datanucleus.ClassLoaderResolver;
import org.datanucleus.ExecutionContext;
import org.datanucleus.PropertyNames;
import org.datanucleus.Transaction;
import org.datanucleus.exceptions.ClassNotResolvedException;
import org.datanucleus.exceptions.ConnectionFactoryNotFoundException;
import org.datanucleus.exceptions.NucleusDataStoreException;
import org.datanucleus.exceptions.NucleusException;
import org.datanucleus.exceptions.NucleusUserException;
import org.datanucleus.exceptions.UnsupportedConnectionFactoryException;
import org.datanucleus.store.StoreManager;
import org.datanucleus.store.connection.AbstractConnectionFactory;
import org.datanucleus.store.connection.AbstractEmulatedXAResource;
import org.datanucleus.store.connection.AbstractManagedConnection;
import org.datanucleus.store.connection.ConnectionFactory;
import org.datanucleus.store.connection.ManagedConnection;
import org.datanucleus.store.rdbms.adapter.DatastoreAdapter;
import org.datanucleus.store.rdbms.connectionpool.ConnectionPool;
import org.datanucleus.store.rdbms.connectionpool.ConnectionPoolFactory;
import org.datanucleus.transaction.TransactionIsolation;
import org.datanucleus.transaction.TransactionUtils;
import org.datanucleus.util.Localiser;
import org.datanucleus.util.NucleusLogger;
import org.datanucleus.util.StringUtils;
/**
* ConnectionFactory for RDBMS datastores.
* Each instance is a factory of Transactional connection or NonTransactional connection.
*/
public class ConnectionFactoryImpl extends AbstractConnectionFactory
{
protected static final Localiser LOCALISER_RDBMS = Localiser.getInstance(
"org.datanucleus.store.rdbms.Localisation", RDBMSStoreManager.class.getClassLoader());
/** Datasources. */
DataSource[] dataSources;
ConnectionPool pool = null;
/**
* Constructor.
* @param storeMgr Store Manager
* @param resourceType either tx or nontx
*/
public ConnectionFactoryImpl(StoreManager storeMgr, String resourceType)
{
super(storeMgr, resourceType);
if (resourceType.equals("tx"))
{
// JTA needs the primary DataSource to be present always
initialiseDataSources();
}
}
/* (non-Javadoc)
* @see org.datanucleus.store.connection.AbstractConnectionFactory#close()
*/
@Override
public void close()
{
if (pool != null)
{
// Close any DataNucleus-created connection pool
if (NucleusLogger.CONNECTION.isDebugEnabled())
{
NucleusLogger.CONNECTION.debug(LOCALISER_RDBMS.msg("047010", resourceType));
}
pool.close();
}
super.close();
}
/**
* Method to initialise the DataSource(s) used by this ConnectionFactory.
* Only invoked when the request for the first connection comes in.
*/
protected synchronized void initialiseDataSources()
{
if (resourceType.equals("tx"))
{
// Transactional
// TODO Remove this, now part of AbstractConnectionFactory
String configuredResourceTypeProperty = storeMgr.getStringProperty(DATANUCLEUS_CONNECTION_RESOURCE_TYPE);
if (configuredResourceTypeProperty != null)
{
if (options == null)
{
options = new HashMap();
}
options.put(ConnectionFactory.RESOURCE_TYPE_OPTION, configuredResourceTypeProperty);
}
String requiredPoolingType = storeMgr.getStringProperty(PropertyNames.PROPERTY_CONNECTION_POOLINGTYPE);
Object connDS = storeMgr.getConnectionFactory();
String connJNDI = storeMgr.getConnectionFactoryName();
String connURL = storeMgr.getConnectionURL();
dataSources = generateDataSources(storeMgr, connDS, connJNDI, resourceType, requiredPoolingType, connURL);
if (dataSources == null)
{
throw new NucleusUserException(LOCALISER_RDBMS.msg("047009", "transactional")).setFatal();
}
}
else
{
// Non-transactional
// TODO Remove this, now part of AbstractConnectionFactory
String configuredResourceTypeProperty = storeMgr.getStringProperty(DATANUCLEUS_CONNECTION2_RESOURCE_TYPE);
if (configuredResourceTypeProperty!=null)
{
if (options == null)
{
options = new HashMap();
}
options.put(ConnectionFactory.RESOURCE_TYPE_OPTION, configuredResourceTypeProperty);
}
String requiredPoolingType = storeMgr.getStringProperty(PropertyNames.PROPERTY_CONNECTION_POOLINGTYPE2);
if (requiredPoolingType == null)
{
requiredPoolingType = storeMgr.getStringProperty(PropertyNames.PROPERTY_CONNECTION_POOLINGTYPE);
}
Object connDS = storeMgr.getConnectionFactory2();
String connJNDI = storeMgr.getConnectionFactory2Name();
String connURL = storeMgr.getConnectionURL();
dataSources = generateDataSources(storeMgr, connDS, connJNDI, resourceType, requiredPoolingType, connURL);
if (dataSources == null)
{
// Fallback to transactional settings
connDS = storeMgr.getConnectionFactory();
connJNDI = storeMgr.getConnectionFactoryName();
dataSources = generateDataSources(storeMgr, connDS, connJNDI, resourceType, requiredPoolingType, connURL);
}
if (dataSources == null)
{
throw new NucleusUserException(LOCALISER_RDBMS.msg("047009", "non-transactional")).setFatal();
}
}
}
/**
* Method to generate the datasource(s) used by this connection factory.
* Searches initially for a provided DataSource, then if not found, for JNDI DataSource(s), and finally
* for the DataSource at a connection URL.
* @param storeMgr Store Manager
* @param connDS Factory data source object
* @param connJNDI DataSource JNDI name(s)
* @param connURL URL for connections
* @return The DataSource(s)
*/
private DataSource[] generateDataSources(StoreManager storeMgr, Object connDS, String connJNDI,
String resourceType, String requiredPoolingType, String connURL)
{
DataSource[] dataSources = null;
if (connDS != null)
{
if (!(connDS instanceof DataSource) && !(connDS instanceof XADataSource))
{
throw new UnsupportedConnectionFactoryException(connDS);
}
dataSources = new DataSource[1];
dataSources[0] = (DataSource) connDS;
}
else if (connJNDI != null)
{
String[] connectionFactoryNames = StringUtils.split(connJNDI, ",");
dataSources = new DataSource[connectionFactoryNames.length];
for (int i=0; i<connectionFactoryNames.length; i++)
{
Object obj;
try
{
obj = new InitialContext().lookup(connectionFactoryNames[i]);
}
catch (NamingException e)
{
throw new ConnectionFactoryNotFoundException(connectionFactoryNames[i], e);
}
if (!(obj instanceof DataSource) && !(obj instanceof XADataSource))
{
throw new UnsupportedConnectionFactoryException(obj);
}
dataSources[i] = (DataSource) obj;
}
}
else if (connURL != null)
{
dataSources = new DataSource[1];
String poolingType = calculatePoolingType(storeMgr, requiredPoolingType);
// User has requested internal database connection pooling so check the registered plugins
try
{
// Create the ConnectionPool to be used
ConnectionPoolFactory connPoolFactory =
(ConnectionPoolFactory)storeMgr.getNucleusContext().getPluginManager().createExecutableExtension(
"org.datanucleus.store.rdbms.connectionpool", "name", poolingType, "class-name", null, null);
if (connPoolFactory == null)
{
// User has specified a pool plugin that has not registered
throw new NucleusUserException(LOCALISER_RDBMS.msg("047003", poolingType)).setFatal();
}
// Create the ConnectionPool and get the DataSource
pool = connPoolFactory.createConnectionPool(storeMgr);
dataSources[0] = pool.getDataSource();
if (NucleusLogger.CONNECTION.isDebugEnabled())
{
NucleusLogger.CONNECTION.debug(LOCALISER_RDBMS.msg("047008", resourceType, poolingType));
}
}
catch (ClassNotFoundException cnfe)
{
throw new NucleusUserException(LOCALISER_RDBMS.msg("047003", poolingType), cnfe).setFatal();
}
catch (Exception e)
{
if (e instanceof InvocationTargetException)
{
InvocationTargetException ite = (InvocationTargetException)e;
throw new NucleusException(LOCALISER_RDBMS.msg("047004", poolingType,
ite.getTargetException().getMessage()), ite.getTargetException()).setFatal();
}
else
{
throw new NucleusException(LOCALISER_RDBMS.msg("047004", poolingType,
e.getMessage()),e).setFatal();
}
}
}
return dataSources;
}
/**
* Method to create a new ManagedConnection.
* @param ec the object that is bound the connection during its lifecycle (if for a PM/EM operation)
* @param options Options for creating the connection (optional)
* @return The ManagedConnection
*/
public ManagedConnection createManagedConnection(ExecutionContext ec, Map options)
{
if (dataSources == null)
{
// Lazy initialisation of DataSource(s)
initialiseDataSources();
}
ManagedConnection mconn = new ManagedConnectionImpl(ec, options);
boolean singleConnection = storeMgr.getBooleanProperty(PropertyNames.PROPERTY_CONNECTION_SINGLE_CONNECTION);
boolean releaseAfterUse = storeMgr.getBooleanProperty(PropertyNames.PROPERTY_CONNECTION_NONTX_RELEASE_AFTER_USE);
if (ec != null && !ec.getTransaction().isActive() && (!releaseAfterUse || singleConnection))
{
// Non-transactional connection and requested not to close on release
mconn.setCloseOnRelease(false);
}
return mconn;
}
class ManagedConnectionImpl extends AbstractManagedConnection
{
ExecutionContext ec;
XAResource xaRes = null;
int isolation;
boolean needsCommitting = false;
ConnectionProvider connProvider = null;
ManagedConnectionImpl(ExecutionContext ec, Map options)
{
if (options != null && options.get(Transaction.TRANSACTION_ISOLATION_OPTION) != null)
{
isolation = ((Number) options.get(Transaction.TRANSACTION_ISOLATION_OPTION)).intValue();
}
else
{
isolation = TransactionUtils.getTransactionIsolationLevelForName(
storeMgr.getStringProperty(PropertyNames.PROPERTY_TRANSACTION_ISOLATION));
}
// Use the required ConnectionProvider
try
{
connProvider = (ConnectionProvider) storeMgr.getNucleusContext().getPluginManager().createExecutableExtension(
"org.datanucleus.store.rdbms.connectionprovider", "name",
storeMgr.getStringProperty(RDBMSPropertyNames.PROPERTY_RDBMS_CONNECTION_PROVIDER_NAME),
"class-name", null, null);
if (connProvider == null)
{
// No provider with this name (missing plugin ?)
throw new NucleusException(LOCALISER_RDBMS.msg("050000",
storeMgr.getStringProperty(RDBMSPropertyNames.PROPERTY_RDBMS_CONNECTION_PROVIDER_NAME))).setFatal();
}
connProvider.setFailOnError(storeMgr.getBooleanProperty(RDBMSPropertyNames.PROPERTY_RDBMS_CONNECTION_PROVIDER_FAIL_ON_ERROR));
}
catch (Exception e)
{
// Error creating provider
throw new NucleusException(LOCALISER_RDBMS.msg("050001",
storeMgr.getStringProperty(RDBMSPropertyNames.PROPERTY_RDBMS_CONNECTION_PROVIDER_NAME), e.getMessage()), e).setFatal();
}
}
/**
* Release this connection.
* Releasing this connection will allow this managed connection to be used one or more times
* inside the same transaction. If this managed connection is managed by a transaction manager,
* release is a no-op, otherwise the physical connection is closed
*/
@Override
public void release()
{
if (commitOnRelease)
{
// Nontransactional context, and need to commit the connection
try
{
Connection conn = getSqlConnection();
if (conn != null && !conn.isClosed() && !conn.getAutoCommit())
{
// Make sure any remaining statements are executed and commit the connection
((RDBMSStoreManager)storeMgr).getSQLController().processConnectionStatement(this);
this.needsCommitting = false;
if (NucleusLogger.CONNECTION.isDebugEnabled())
{
NucleusLogger.CONNECTION.debug(LOCALISER.msg("009015", this.toString()));
}
conn.commit();
}
}
catch (SQLException sqle)
{
throw new NucleusDataStoreException(sqle.getMessage(), sqle);
}
}
super.release();
}
/**
* Obtain an XAResource which can be enlisted in a transaction
*/
@Override
public XAResource getXAResource()
{
if (xaRes != null)
{
return xaRes;
}
if (getConnection() instanceof Connection)
{
xaRes = new EmulatedXAResource(this);
}
else
{
try
{
xaRes = ((XAConnection)getConnection()).getXAResource();
}
catch (SQLException e)
{
throw new NucleusDataStoreException(e.getMessage(),e);
}
}
return xaRes;
}
/**
* Create a connection to the resource
*/
public Object getConnection()
{
if (this.conn == null)
{
Connection cnx = null;
try
{
RDBMSStoreManager rdbmsMgr = (RDBMSStoreManager)storeMgr;
boolean readOnly = ec != null ? ec.getBooleanProperty(PropertyNames.PROPERTY_DATASTORE_READONLY) : storeMgr.getBooleanProperty(PropertyNames.PROPERTY_DATASTORE_READONLY);
if (rdbmsMgr.getDatastoreAdapter() != null)
{
// Create Connection following DatastoreAdapter capabilities
DatastoreAdapter rdba = rdbmsMgr.getDatastoreAdapter();
int reqdIsolationLevel = isolation;
if (rdba.getRequiredTransactionIsolationLevel() >= 0)
{
// Override with the adapters required isolation level
reqdIsolationLevel = rdba.getRequiredTransactionIsolationLevel();
}
cnx = connProvider.getConnection(dataSources);
boolean succeeded = false;
try
{
if (cnx.isReadOnly() != readOnly)
{
NucleusLogger.CONNECTION.debug("Setting readonly=" + readOnly + " to connection: " + cnx.toString());
cnx.setReadOnly(readOnly);
}
if (reqdIsolationLevel == TransactionIsolation.NONE)
{
if (!cnx.getAutoCommit())
{
cnx.setAutoCommit(true);
}
}
else
{
if (cnx.getAutoCommit())
{
cnx.setAutoCommit(false);
}
if (rdba.supportsTransactionIsolation(reqdIsolationLevel))
{
int currentIsolationLevel = cnx.getTransactionIsolation();
if (currentIsolationLevel != reqdIsolationLevel)
{
cnx.setTransactionIsolation(reqdIsolationLevel);
}
}
else
{
NucleusLogger.CONNECTION.warn(LOCALISER_RDBMS.msg("051008", reqdIsolationLevel));
}
}
if (NucleusLogger.CONNECTION.isDebugEnabled())
{
NucleusLogger.CONNECTION.debug(LOCALISER.msg("009012", this.toString(),
TransactionUtils.getNameForTransactionIsolationLevel(reqdIsolationLevel),
cnx.getAutoCommit()));
}
if (reqdIsolationLevel != isolation && isolation == TransactionIsolation.NONE)
{
// User asked for a level that implies auto-commit so make sure it has that
if (!cnx.getAutoCommit())
{
NucleusLogger.CONNECTION.debug("Setting autocommit=true for connection: "+StringUtils.toJVMIDString(cnx));
cnx.setAutoCommit(true);
}
}
succeeded = true;
}
catch (SQLException e)
{
throw new NucleusDataStoreException(e.getMessage(),e);
}
finally
{
if (!succeeded)
{
try
{
cnx.close();
}
catch (SQLException e)
{
}
if (NucleusLogger.CONNECTION.isDebugEnabled())
{
NucleusLogger.CONNECTION.debug(LOCALISER.msg("009013", this.toString()));
}
}
}
}
else
{
// Create basic Connection since no DatastoreAdapter created yet
cnx = dataSources[0].getConnection();
if (cnx == null)
{
String msg = LOCALISER.msg("009010", dataSources[0]);
NucleusLogger.CONNECTION.error(msg);
throw new NucleusDataStoreException(msg);
}
if (NucleusLogger.CONNECTION.isDebugEnabled())
{
NucleusLogger.CONNECTION.debug(LOCALISER.msg("009011", this.toString()));
}
}
}
catch (SQLException e)
{
throw new NucleusDataStoreException(e.getMessage(),e);
}
this.conn = cnx;
}
needsCommitting = true;
return this.conn;
}
/**
* Close the connection
*/
public void close()
{
for (int i=0; i<listeners.size(); i++)
{
listeners.get(i).managedConnectionPreClose();
}
Connection conn = getSqlConnection();
if (conn != null)
{
try
{
if (commitOnRelease && needsCommitting)
{
// Non-transactional context, so need to commit the connection
if (!conn.isClosed() && !conn.getAutoCommit())
{
// Make sure any remaining statements are executed and commit the connection
SQLController sqlController = ((RDBMSStoreManager)storeMgr).getSQLController();
if (sqlController != null)
{
sqlController.processConnectionStatement(this);
}
conn.commit();
needsCommitting = false;
if (NucleusLogger.CONNECTION.isDebugEnabled())
{
NucleusLogger.CONNECTION.debug(LOCALISER.msg("009015", this.toString()));
}
}
}
}
catch (SQLException sqle)
{
throw new NucleusDataStoreException(sqle.getMessage(), sqle);
}
finally
{
try
{
if (!conn.isClosed())
{
if (NucleusLogger.CONNECTION.isDebugEnabled())
{
NucleusLogger.CONNECTION.debug(LOCALISER.msg("009013", this.toString()));
}
conn.close();
}
else
{
if (NucleusLogger.CONNECTION.isDebugEnabled())
{
NucleusLogger.CONNECTION.debug(LOCALISER.msg("009014", this.toString()));
}
}
}
catch (SQLException sqle)
{
throw new NucleusDataStoreException(sqle.getMessage(), sqle);
}
}
}
try
{
for (int i=0; i<listeners.size(); i++)
{
listeners.get(i).managedConnectionPostClose();
}
}
finally
{
listeners.clear();
}
if (savepoints != null)
{
savepoints.clear();
savepoints = null;
}
this.conn = null;
this.xaRes = null;
}
/**
* Convenience accessor for the java.sql.Connection in use (if any).
* @return SQL Connection
*/
private Connection getSqlConnection()
{
if (this.conn != null && this.conn instanceof Connection)
{
return (Connection) this.conn;
}
else if (this.conn != null && this.conn instanceof XAConnection)
{
try
{
return ((XAConnection) this.conn).getConnection();
}
catch (SQLException e)
{
throw new NucleusDataStoreException(e.getMessage(), e);
}
}
return null;
}
private Map<String, Savepoint> savepoints = null;
/* (non-Javadoc)
* @see org.datanucleus.store.connection.AbstractManagedConnection#setSavepoint(java.lang.String)
*/
@Override
public void setSavepoint(String name)
{
try
{
Savepoint sp = ((Connection)conn).setSavepoint(name);
if (savepoints == null)
{
savepoints = new HashMap<String, Savepoint>();
}
savepoints.put(name, sp);
}
catch (SQLException sqle)
{
throw new NucleusDataStoreException("Exception setting savepoint " + name, sqle);
}
}
/* (non-Javadoc)
* @see org.datanucleus.store.connection.AbstractManagedConnection#releaseSavepoint(java.lang.String)
*/
@Override
public void releaseSavepoint(String name)
{
try
{
if (savepoints == null)
{
return;
}
Savepoint sp = savepoints.remove(name);
if (sp == null)
{
throw new IllegalStateException("No savepoint with name " + name);
}
((Connection)conn).releaseSavepoint(sp);
}
catch (SQLException sqle)
{
throw new NucleusDataStoreException("Exception releasing savepoint " + name, sqle);
}
}
/* (non-Javadoc)
* @see org.datanucleus.store.connection.AbstractManagedConnection#rollbackToSavepoint(java.lang.String)
*/
@Override
public void rollbackToSavepoint(String name)
{
try
{
if (savepoints == null)
{
return;
}
Savepoint sp = savepoints.get(name);
if (sp == null)
{
throw new IllegalStateException("No savepoint with name " + name);
}
((Connection)conn).rollback(sp);
}
catch (SQLException sqle)
{
throw new NucleusDataStoreException("Exception rolling back to savepoint " + name, sqle);
}
}
/* (non-Javadoc)
* @see org.datanucleus.store.connection.AbstractManagedConnection#closeAfterTransactionEnd()
*/
@Override
public boolean closeAfterTransactionEnd()
{
if (storeMgr.getBooleanProperty(PropertyNames.PROPERTY_CONNECTION_SINGLE_CONNECTION))
{
return false;
}
return super.closeAfterTransactionEnd();
}
}
/**
* Emulate the two phase protocol for non XA
*/
static class EmulatedXAResource extends AbstractEmulatedXAResource
{
Connection conn;
EmulatedXAResource(ManagedConnection mconn)
{
super(mconn);
this.conn = (Connection) mconn.getConnection();
}
public void commit(Xid xid, boolean onePhase) throws XAException
{
super.commit(xid, onePhase);
try
{
conn.commit();
((ManagedConnectionImpl)mconn).xaRes = null;
}
catch (SQLException e)
{
NucleusLogger.CONNECTION.debug(LOCALISER.msg("009020", mconn.toString(), xid.toString(), onePhase));
XAException xe = new XAException(StringUtils.getStringFromStackTrace(e));
xe.initCause(e);
throw xe;
}
}
public void rollback(Xid xid) throws XAException
{
super.rollback(xid);
try
{
conn.rollback();
((ManagedConnectionImpl)mconn).xaRes = null;
}
catch (SQLException e)
{
NucleusLogger.CONNECTION.debug(LOCALISER.msg("009022", mconn.toString(), xid.toString()));
XAException xe = new XAException(StringUtils.getStringFromStackTrace(e));
xe.initCause(e);
throw xe;
}
}
public void end(Xid xid, int flags) throws XAException
{
super.end(xid, flags);
((ManagedConnectionImpl)mconn).xaRes = null;
}
}
/**
* Method to set the connection pooling type (if any).
* Tries to use any user-provided value if possible, otherwise will fallback to something
* available in the CLASSPATH (if any), else use the builtin DBCP.
* @param storeMgr Store Manager
* @param requiredPoolingType Pooling type requested by the user
* @return Pooling type to use (name of a pool type)
*/
protected static String calculatePoolingType(StoreManager storeMgr, String requiredPoolingType)
{
String poolingType = requiredPoolingType;
ClassLoaderResolver clr = storeMgr.getNucleusContext().getClassLoaderResolver(null);
if (poolingType != null)
{
// User-specified, so check availability
if (poolingType.equalsIgnoreCase("DBCP") && !dbcpPresent(clr))
{
NucleusLogger.CONNECTION.warn("DBCP specified but not present in CLASSPATH (or one of dependencies)");
poolingType = null;
}
else if (poolingType.equalsIgnoreCase("C3P0") && !c3p0Present(clr))
{
NucleusLogger.CONNECTION.warn("C3P0 specified but not present in CLASSPATH (or one of dependencies)");
poolingType = null;
}
else if (poolingType.equalsIgnoreCase("Proxool") && !proxoolPresent(clr))
{
NucleusLogger.CONNECTION.warn("Proxool specified but not present in CLASSPATH (or one of dependencies)");
poolingType = null;
}
else if (poolingType.equalsIgnoreCase("BoneCP") && !bonecpPresent(clr))
{
NucleusLogger.CONNECTION.warn("BoneCP specified but not present in CLASSPATH (or one of dependencies)");
poolingType = null;
}
}
// Not specified, so try to find one in the CLASSPATH
if (poolingType == null && dbcpPresent(clr))
{
poolingType = "DBCP";
}
if (poolingType == null && c3p0Present(clr))
{
poolingType = "C3P0";
}
if (poolingType == null && proxoolPresent(clr))
{
poolingType = "Proxool";
}
if (poolingType == null && bonecpPresent(clr))
{
poolingType = "BoneCP";
}
if (poolingType == null)
{
// Fallback to built-in DBCP (JDK1.6+)
poolingType = "dbcp-builtin";
}
return poolingType;
}
protected static boolean dbcpPresent(ClassLoaderResolver clr)
{
try
{
// Need commons-dbcp, commons-pool, commons-collections
clr.classForName("org.apache.commons.pool.ObjectPool");
clr.classForName("org.apache.commons.dbcp.ConnectionFactory");
return true;
}
catch (ClassNotResolvedException cnre)
{
// DBCP not available
return false;
}
}
protected static boolean c3p0Present(ClassLoaderResolver clr)
{
try
{
// Need c3p0
clr.classForName("com.mchange.v2.c3p0.ComboPooledDataSource");
return true;
}
catch (ClassNotResolvedException cnre)
{
// C3P0 not available
return false;
}
}
protected static boolean proxoolPresent(ClassLoaderResolver clr)
{
try
{
// Need proxool, commons-logging
clr.classForName("org.logicalcobwebs.proxool.ProxoolDriver");
clr.classForName("org.apache.commons.logging.Log");
return true;
}
catch (ClassNotResolvedException cnre)
{
// Proxool not available
return false;
}
}
protected static boolean bonecpPresent(ClassLoaderResolver clr)
{
try
{
// Need bonecp, slf4j, google-collections
clr.classForName("com.jolbox.bonecp.BoneCPDataSource");
clr.classForName("org.slf4j.Logger");
clr.classForName("com.google.common.collect.Multiset");
return true;
}
catch (ClassNotResolvedException cnre)
{
// BoneCP not available
return false;
}
}
}