Statistics
| Revision:

svn-gvsig-desktop / branches / v10 / libraries / libFMap / src / com / iver / cit / gvsig / fmap / drivers / db / utils / SingleVectorialDBConnectionManager.java @ 11928

History | View | Annotate | Download (7.75 KB)

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

    
3
import java.util.ArrayList;
4
import java.util.HashMap;
5
import java.util.Iterator;
6

    
7
import org.apache.log4j.Logger;
8

    
9
import com.iver.cit.gvsig.fmap.drivers.ConnectionFactory;
10
import com.iver.cit.gvsig.fmap.drivers.DBException;
11
import com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver;
12
import com.iver.cit.gvsig.fmap.drivers.IConnection;
13
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
14

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

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

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

    
34
        }
35

    
36
        /**
37
         * Singleton model to keep single instances.
38
         *
39
         * @return single instance
40
         */
41
        public static SingleVectorialDBConnectionManager instance() {
42
                if (single_instance == null) {
43
                        single_instance = new SingleVectorialDBConnectionManager();
44
                }
45
                return single_instance;
46
        }
47

    
48
        /**
49
         * Utility metho to find a connection with its parameters
50
         * given the connection object.
51
         *
52
         * @param co the connection object
53
         * @return
54
         */
55
        public ConnectionWithParams findConnection(IConnection co) {
56

    
57
                Iterator iter = connections.keySet().iterator();
58
                while (iter.hasNext()) {
59
                        String keyitem = (String) iter.next();
60
                        ConnectionWithParams cwp = (ConnectionWithParams) connections.get(keyitem);
61
                        if (cwp.getConnection() == co) {
62
                                return cwp;
63
                        }
64
                }
65
                return null;
66
        }
67

    
68

    
69
        /**
70
         * Creates a new connection with its parameters if not created yet.
71
         *
72
         * @param _drvName driver name
73
         * @param _user user name
74
         * @param _pw password
75
         * @param _name connection name
76
         * @param _host host url
77
         * @param _port port number as string
78
         * @param _db database name
79
         * @param _connected whether or not to connect the connection
80
         * @return the connection with parameters object
81
         * @throws SQLException
82
         */
83
        public ConnectionWithParams getConnection (
84
                        String _drvName,
85
                        String _user,
86
                        String _pw,
87
                        String _name,
88
                        String _host,
89
                        String _port,
90
                        String _db,
91
                        boolean _connected
92
                        ) throws DBException {
93

    
94
                IVectorialDatabaseDriver drv = getInstanceFromName(_drvName);
95
                if (drv==null)return null;
96
                String conn_str = drv.getConnectionString(_host, _port, _db, _user, _pw);
97

    
98
                String key = getConnectionKey(_drvName, _host, _db, _port, _user);
99

    
100
                if (!connections.containsKey(key)) {
101

    
102
                        ConnectionWithParams cwp = null;
103

    
104
                        if (_connected) {
105
                                IConnection new_connection = null;
106
                                new_connection = ConnectionFactory.createConnection(conn_str, _user, _pw);
107

    
108
//                                new_connection.setAutoCommit(false);
109

    
110
                                cwp = new ConnectionWithParams(
111
                                                conn_str,
112
                                                new_connection,
113
                                                _drvName,
114
                                                _user,
115
                                                _pw,
116
                                                _name,
117
                                                _host,
118
                                                _port,
119
                                                _db,
120
                                                true);
121
                        } else {
122

    
123
                                cwp = new ConnectionWithParams(
124
                                                conn_str,
125
                                                null,
126
                                                _drvName,
127
                                                _user,
128
                                                null,
129
                                                _name,
130
                                                _host,
131
                                                _port,
132
                                                _db,
133
                                                false);
134
                        }
135
                        connections.put(key, cwp);
136
                }
137

    
138
                ConnectionWithParams _cwp = (ConnectionWithParams) connections.get(key);
139

    
140
                if (_cwp.getName().compareTo(_name) != 0) {
141
                        // connections.remove(key);
142
                        _cwp.setName(_name);
143
                        connections.put(key, _cwp);
144
                }
145

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

    
150
                return _cwp;
151
        }
152

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

    
162
                ArrayList aux = new ArrayList();
163

    
164
                while (iter.hasNext()) {
165
                        ConnectionWithParams _cwp =
166
                                (ConnectionWithParams) connections.get(iter.next());
167
                        if (_cwp.isConnected()) {
168
                                aux.add(_cwp);
169
                        }
170
                }
171

    
172
                ConnectionWithParams[] resp = new ConnectionWithParams[aux.size()];
173
                for (int i=0; i<aux.size(); i++) {
174
                        resp[i] = (ConnectionWithParams) aux.get(i);
175
                }
176
                return resp;
177
        }
178

    
179
        /**
180
         * Gets all available connections.
181
         *
182
         * @return array of all connections with parameters
183
         */
184
        public ConnectionWithParams[] getAllConnections() {
185
                Iterator iter = connections.keySet().iterator();
186
                if (!iter.hasNext()) return null;
187

    
188
                ArrayList aux = new ArrayList();
189

    
190
                while (iter.hasNext()) {
191
                        ConnectionWithParams _cwp =
192
                                (ConnectionWithParams) connections.get(iter.next());
193
                        aux.add(_cwp);
194
                }
195

    
196
                ConnectionWithParams[] resp = new ConnectionWithParams[aux.size()];
197
                for (int i=0; i<aux.size(); i++) {
198
                        resp[i] = (ConnectionWithParams) aux.get(i);
199
                }
200
                return resp;
201
        }
202

    
203
        /**
204
         * Removes connection with its params.
205
         *
206
         * @param _cwp connection with params to be removed
207
         */
208
        private void removeConnectionWP(ConnectionWithParams _cwp) {
209

    
210
                ArrayList keysToRemove = new ArrayList();
211

    
212
                Iterator iter = connections.keySet().iterator();
213
                while (iter.hasNext()) {
214
                        Object key = iter.next();
215
                        ConnectionWithParams cwp = (ConnectionWithParams) connections.get(key);
216
                        if (cwp == _cwp) {
217
                                keysToRemove.add(key);
218
                        }
219
                }
220
                for (int i=0; i<keysToRemove.size(); i++) {
221
                        connections.remove(keysToRemove.get(i));
222
                }
223
        }
224

    
225

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

    
235
                boolean it_was_open = true;
236

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

    
249
        /**
250
         * Called by the extension object when gvsig terminates.
251
         *
252
         */
253
        public void closeAllBeforeTerminate() {
254

    
255
                boolean ok = true;
256
                String key = "";
257
                ConnectionWithParams cwp = null;
258
                Iterator iter = connections.keySet().iterator();
259
                while (iter.hasNext()) {
260
                        key = (String) iter.next();
261
                        cwp = (ConnectionWithParams) connections.get(key);
262

    
263
                        if (cwp.getConnection() == null) continue;
264

    
265
                        try {
266
                                cwp.getConnection().close();
267
                        } catch (DBException se) {
268
                                ok = false;
269
                                logger.error("While closing connection: " + se.getMessage(), se);
270
                        }
271
                }
272

    
273
                connections.clear();
274

    
275
                if (ok) {
276
                        logger.info("Successfully closed all connections.");
277
                } else {
278
                        logger.warn("Problems while closing all connections.");
279
                }
280
        }
281

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

    
297
                String resp = "_driver_" + _drvName.toLowerCase();
298
                resp = resp + "_host_" + _host.toLowerCase();
299
                resp = resp + "_db_" + _db.toLowerCase(); // ---------------- nueva
300
                resp = resp + "_port_" + _port;
301
                resp = resp + "_user_" + _user.toLowerCase();
302
                return resp;
303
        }
304

    
305
        /**
306
         * Utility method to instantiate a driver given its name.
307
         *
308
         * @param drvname driver name
309
         * @return driver instance
310
         */
311
        public static IVectorialDatabaseDriver getInstanceFromName(String drvname) {
312

    
313
                IVectorialDatabaseDriver _driver = null;
314
        try {
315
            _driver = (IVectorialDatabaseDriver) LayerFactory.getDM().getDriver(drvname);
316
        } catch (Exception e) {
317
                logger.error("While getting driver instance: " + e.getMessage(), e);
318
        }
319
        return _driver;
320
        }
321

    
322

    
323

    
324

    
325

    
326
}