1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.millscript.millscript.datatypes;
23
24 import org.millscript.millscript.alert.Alerts;
25
26 import java.io.File;
27 import java.sql.Connection;
28 import java.sql.SQLException;
29
30 import javax.sql.DataSource;
31
32 /**
33 * This class is a wrapper for a DataSource. It allows millscript to share a
34 * database connection between multiple functions, as created by the SQL loader.
35 *
36 * @since 9.6.4
37 */
38 public class DatabaseSource {
39
40 /**
41 * The DataSource we will obtain connections from.
42 */
43 private DataSource dataSource;
44
45 /**
46 * The Connection we will supply on request.
47 */
48 private Connection connection;
49
50 /**
51 * The name of this database source
52 */
53 private String name;
54
55 /**
56 * The lockfile for this database source
57 */
58 private File lockFile;
59
60 /**
61 * Constructs a new DatabaseSource using the supplied DataSource.
62 *
63 * @param n the DataSource name
64 * @param ds the DataSource to wrap.
65 * @param lf the DataSource lockfile, or <code>null</code> if there is no
66 * lockfile
67 */
68 public DatabaseSource( final String n, final DataSource ds, final File lf ) {
69 this.dataSource = ds;
70 this.name = n;
71 this.lockFile = lf;
72 }
73
74 /**
75 * Returns a connection to the database detailed in this DataSource.
76 *
77 * @return the connection to the database
78 */
79 public Connection getConnection() {
80 try {
81
82
83 if ( connection == null || connection.isClosed() ) {
84
85
86 if ( lockFile == null || lockFile.exists() ) {
87 connection = dataSource.getConnection();
88
89
90 connection.setAutoCommit( true );
91 } else {
92 throw(
93 Alerts.eval(
94 "Could not get a connection to the database",
95 "The database is currently locked"
96 ).culprit( "lockfile", lockFile ).mishap()
97 );
98 }
99 }
100 } catch ( SQLException ex ) {
101 throw(
102 Alerts.eval(
103 "Could not get connection to database",
104 null
105 ).culprit( "BECAUSE", ex.getMessage() ).mishap()
106 );
107 }
108 return connection;
109 }
110
111 /**
112 * Returns a string representation of this database source.
113 *
114 * @return a string representing this database source
115 */
116 @Override
117 public String toString() {
118 return name == null ?
119 "<connection>" :
120 "<connection name=\"" + name + "\">";
121 }
122
123 }