Statistics
| Revision:

svn-gvsig-desktop / branches / simbologia / libraries / libFMap / src / com / iver / cit / gvsig / fmap / drivers / jdbc / utils / SingleJDBCConnectionManager.java @ 10450

History | View | Annotate | Download (7.52 KB)

1
package com.iver.cit.gvsig.fmap.drivers.jdbc.utils;
2

    
3
import java.sql.Connection;
4
import java.sql.DriverManager;
5
import java.sql.SQLException;
6
import java.util.ArrayList;
7
import java.util.HashMap;
8
import java.util.Iterator;
9

    
10
import org.apache.log4j.Logger;
11
import com.iver.cit.gvsig.fmap.drivers.DefaultDBDriver;
12
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
13

    
14
/**
15
 * Utility class to handle connections properly. One connection instance per
16
 * (db, user, gvsig session)
17
 * 
18
 * @author jldominguez
19
 *
20
 */
21
public class SingleJDBCConnectionManager {
22

    
23
        private static Logger logger = Logger.getLogger(SingleJDBCConnectionManager.class.getName());
24
        private static SingleJDBCConnectionManager single_instance = null;
25
        private HashMap connections = new HashMap();
26

    
27
        /**
28
         * Non-public to avoid unwanted instances.
29
         *
30
         */
31
        protected SingleJDBCConnectionManager() {
32

    
33
        }
34

    
35
        /**
36
         * Singleton model to keep single instances.
37
         * 
38
         * @return single instance
39
         */
40
        public static SingleJDBCConnectionManager instance() {
41
                if (single_instance == null) {
42
                        single_instance = new SingleJDBCConnectionManager();
43
                }
44
                return single_instance;
45
        }
46
        
47
        /**
48
         * Utility metho to find a connection with its parameters
49
         * given the connection object.
50
         * 
51
         * @param co the connection object
52
         * @return
53
         */
54
        public ConnectionWithParams findConnection(Connection co) {
55
                
56
                Iterator iter = connections.keySet().iterator();
57
                while (iter.hasNext()) {
58
                        String keyitem = (String) iter.next();
59
                        ConnectionWithParams cwp = (ConnectionWithParams) connections.get(keyitem);
60
                        if (cwp.getConnection() == co) {
61
                                return cwp;
62
                        }
63
                }
64
                return null;
65
        }
66

    
67

    
68
        /**
69
         * Creates a new connection with its parameters if not created yet.
70
         * 
71
         * @param _drvName driver name
72
         * @param _user user name
73
         * @param _pw password
74
         * @param _name connection name
75
         * @param _host host url
76
         * @param _port port number as string
77
         * @param _db databade name
78
         * @param _connected whether or not to connect the connection
79
         * @return the connection with parameters object
80
         * @throws SQLException
81
         */
82
        public ConnectionWithParams getConnection (
83
                        String _drvName,
84
                        String _user,
85
                        String _pw,
86
                        String _name,
87
                        String _host,
88
                        String _port,
89
                        String _db,
90
                        boolean _connected
91
                        ) throws SQLException {
92
                
93
                DefaultDBDriver drv = getInstanceFromName(_drvName);
94
                String conn_str = drv.getConnectionString(_host, _port, _db, _user, _pw);
95
                
96
                String key = getConnectionKey(_drvName, _host, _port, _user);
97
                
98
                if (!connections.containsKey(key)) {
99
                        
100
                        ConnectionWithParams cwp = null;
101
                        
102
                        if (_connected) {
103
                                Connection new_connection = null;
104
                                new_connection = DriverManager.getConnection(conn_str, _user, _pw);
105

    
106
                                new_connection.setAutoCommit(false);
107
                                
108
                                cwp = new ConnectionWithParams(
109
                                                conn_str,
110
                                                new_connection,
111
                                                _drvName,
112
                                                _user,
113
                                                _pw,
114
                                                _name,
115
                                                _host,
116
                                                _port,
117
                                                _db,
118
                                                true);
119
                        } else {
120
                                
121
                                cwp = new ConnectionWithParams(
122
                                                conn_str,
123
                                                null,
124
                                                _drvName,
125
                                                _user,
126
                                                null,
127
                                                _name,
128
                                                _host,
129
                                                _port,
130
                                                _db,
131
                                                false);
132
                        }
133
                        connections.put(key, cwp);
134
                }
135
                
136
                ConnectionWithParams _cwp = (ConnectionWithParams) connections.get(key);
137
                
138
                if (_cwp.getName().compareTo(_name) != 0) {
139
                        // connections.remove(key);
140
                        _cwp.setName(_name);
141
                        connections.put(key, _cwp);
142
                }
143

    
144
                if ((!_cwp.isConnected()) && (_connected)) {
145
                        _cwp.connect(_pw);
146
                }
147
                
148
                return _cwp;
149
        }
150

    
151
        /**
152
         * Gets available open connections.
153
         *  
154
         * @return array of open connections with parameters
155
         */
156
        public ConnectionWithParams[] getConnectedConnections() {
157
                Iterator iter = connections.keySet().iterator();
158
                if (!iter.hasNext()) return null;
159
                
160
                ArrayList aux = new ArrayList();
161

    
162
                while (iter.hasNext()) {
163
                        ConnectionWithParams _cwp =
164
                                (ConnectionWithParams) connections.get(iter.next());
165
                        if (_cwp.isConnected()) {
166
                                aux.add(_cwp);
167
                        }
168
                }
169
                
170
                ConnectionWithParams[] resp = new ConnectionWithParams[aux.size()];
171
                for (int i=0; i<aux.size(); i++) {
172
                        resp[i] = (ConnectionWithParams) aux.get(i);
173
                }
174
                return resp;
175
        }
176
        
177
        /**
178
         * Gets all available connections.
179
         *  
180
         * @return array of all connections with parameters
181
         */
182
        public ConnectionWithParams[] getAllConnections() {
183
                Iterator iter = connections.keySet().iterator();
184
                if (!iter.hasNext()) return null;
185
                
186
                ArrayList aux = new ArrayList();
187

    
188
                while (iter.hasNext()) {
189
                        ConnectionWithParams _cwp =
190
                                (ConnectionWithParams) connections.get(iter.next());
191
                        aux.add(_cwp);
192
                }
193
                
194
                ConnectionWithParams[] resp = new ConnectionWithParams[aux.size()];
195
                for (int i=0; i<aux.size(); i++) {
196
                        resp[i] = (ConnectionWithParams) aux.get(i);
197
                }
198
                return resp;
199
        }
200
        
201
        /**
202
         * Removes connection with its params.
203
         * 
204
         * @param _cwp connection with params to be removed
205
         */
206
        private void removeConnectionWP(ConnectionWithParams _cwp) {
207
                
208
                ArrayList keysToRemove = new ArrayList();
209
                
210
                Iterator iter = connections.keySet().iterator();
211
                while (iter.hasNext()) {
212
                        Object key = iter.next();
213
                        ConnectionWithParams cwp = (ConnectionWithParams) connections.get(key);  
214
                        if (cwp == _cwp) {
215
                                keysToRemove.add(key);
216
                        }
217
                }
218
                for (int i=0; i<keysToRemove.size(); i++) {
219
                        connections.remove(keysToRemove.get(i));
220
                }
221
        }
222

    
223

    
224
        /**
225
         * Closes and removes a connection with params object
226
         * 
227
         * @param _cwp
228
         * @return whether the connection was actually closed (false if the
229
         * connection was not open at the start)
230
         */
231
        public boolean closeAndRemove(ConnectionWithParams _cwp) {
232
                
233
                boolean it_was_open = true;
234

    
235
                try {
236
                        it_was_open = (_cwp.getConnection() != null) && (!_cwp.getConnection().isClosed());
237
                        if (_cwp.getConnection() != null) _cwp.getConnection().close();
238
                        removeConnectionWP(_cwp);
239
                } catch (Exception se) {
240
                        logger.error("While closing connection: " + se.getMessage(), se);
241
                        return false;
242
                }
243
                logger.info("Connection successfully closed.");
244
                return it_was_open;
245
        }
246

    
247
        /**
248
         * Called by the extension object when gvsig terminates.
249
         *
250
         */
251
        public void closeAllBeforeTerminate() {
252
                
253
                boolean ok = true;
254
                String key = "";
255
                ConnectionWithParams cwp = null;
256
                Iterator iter = connections.keySet().iterator();
257
                while (iter.hasNext()) {
258
                        key = (String) iter.next();
259
                        cwp = (ConnectionWithParams) connections.get(key);
260
                        
261
                        if (cwp.getConnection() == null) continue;
262

    
263
                        try {
264
                                cwp.getConnection().close();
265
                        } catch (SQLException se) {
266
                                ok = false;
267
                                logger.error("While closing connection: " + se.getMessage(), se);
268
                        }
269
                }
270
                
271
                connections.clear();
272
                
273
                if (ok) {
274
                        logger.info("Successfully closed all connections.");
275
                } else {
276
                        logger.warn("Problems while closing all connections.");
277
                }
278
        }
279

    
280
        /**
281
         * Gets the objects key to be used in the inner hashmap
282
         * @param _drvName driver name
283
         * @param _host host's url
284
         * @param _port port number
285
         * @param _user user name
286
         * @return
287
         */
288
        private static String getConnectionKey(
289
                        String _drvName,
290
                        String _host,
291
                        String _port,
292
                        String _user) {
293

    
294
                String resp = "_driver_" + _drvName.toLowerCase();
295
                resp = resp + "_host_" + _host.toLowerCase();
296
                resp = resp + "_port_" + _port;
297
                resp = resp + "_user_" + _user.toLowerCase();
298
                return resp;
299
        }
300

    
301
        /**
302
         * Utility method to instantiate a driver given its name.
303
         * 
304
         * @param drvname driver name
305
         * @return driver instance
306
         */
307
        public static DefaultDBDriver getInstanceFromName(String drvname) {
308
                
309
                DefaultDBDriver _driver = null;
310
        try {
311
            _driver = (DefaultDBDriver) LayerFactory.getDM().getDriver(drvname);
312
        } catch (Exception e) {
313
                logger.error("While getting driver instance: " + e.getMessage(), e);
314
        }
315
        return _driver;
316
        }
317
        
318
        
319
        
320
        
321

    
322
}