Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.compat.cdc / org.gvsig.fmap.dal / org.gvsig.fmap.dal.db / org.gvsig.fmap.dal.db.mdb / src / main / java / org / gvsig / fmap / dal / store / mdb / MDBHelper.java @ 44916

History | View | Annotate | Download (14 KB)

1
/* gvSIG. Geographic Information System of the Valencian Government
2
 *
3
 * Copyright (C) 2007-2016 Infrastructures and Transports Department
4
 * of the Valencian Government (CIT)
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 */
22
package org.gvsig.fmap.dal.store.mdb;
23

    
24
import java.sql.Connection;
25
import java.sql.SQLException;
26
import java.text.MessageFormat;
27
import org.apache.commons.dbcp.BasicDataSource;
28
import org.apache.commons.io.FilenameUtils;
29
import org.apache.commons.lang3.StringUtils;
30
import org.gvsig.expressionevaluator.GeometryExpressionBuilderHelper.GeometrySupportType;
31
import org.gvsig.fmap.dal.exception.InitializeException;
32
import org.gvsig.fmap.dal.resource.exception.AccessResourceException;
33
import org.gvsig.fmap.dal.spi.DataServerExplorerProviderServices;
34
import org.gvsig.fmap.dal.store.mdb.operations.MDBOperationsFactory;
35
import org.gvsig.fmap.dal.store.jdbc.JDBCConnectionParameters;
36
import org.gvsig.fmap.dal.store.jdbc.JDBCNewStoreParameters;
37
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParameters;
38
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
39
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCDriverClassNotFoundException;
40
import org.gvsig.fmap.dal.store.jdbc2.JDBCServerExplorer;
41
import org.gvsig.fmap.dal.store.jdbc2.OperationsFactory;
42
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCHelperBase;
43
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
44
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCServerExplorerBase;
45
import org.gvsig.fmap.dal.store.jdbc2.spi.SRSSolverBase;
46
//import org.h2.tools.Server;
47
//import org.h2gis.ext.H2GISExtension;
48
import org.slf4j.Logger;
49
import org.slf4j.LoggerFactory;
50

    
51
@SuppressWarnings("UseSpecificCatch")
52
public class MDBHelper extends JDBCHelperBase {
53

    
54
    static final Logger LOGGER = LoggerFactory.getLogger(MDBHelper.class);
55

    
56
    public static final String MDBSPATIAL_JDBC_DRIVER = "org.mdb.Driver";
57
    
58
    public static String getConnectionURL(MDBConnectionParameters params) {
59
        String connectionURL;
60
        String dbfilename = params.getFile().getAbsolutePath().replace("\\","/");
61
        if( dbfilename!=null && dbfilename.endsWith(".mv.db") ) {
62
            dbfilename = dbfilename.substring(0, dbfilename.length()-6);
63
        }
64
        StringBuilder commonParameters = new StringBuilder();
65
        commonParameters.append(";MODE=PostgreSQL");
66
        commonParameters.append(";SCHEMA=PUBLIC");
67
        commonParameters.append(";ALLOW_LITERALS=ALL");
68
        
69
//        Integer LOCK_TIMEOUT = (Integer) params.getDynValue("LOCK_TIMEOUT");
70
//        if( LOCK_TIMEOUT!=null ) {
71
//            commonParameters.append(";LOCK_TIMEOUT=").append(LOCK_TIMEOUT);
72
//        }
73
//        Integer MULTI_THREADED = (Integer) params.getDynValue("MULTI_THREADED");
74
//        if( MULTI_THREADED!=null ) {
75
//            commonParameters.append(";MULTI_THREADED=").append(MULTI_THREADED);
76
//        }
77
//        Integer CHACHE_SIZE = (Integer) params.getDynValue("CHACHE_SIZE");
78
//        if( LOCK_TIMEOUT!=null ) {
79
//            commonParameters.append(";CHACHE_SIZE=").append(CHACHE_SIZE);
80
//        }
81
//        Integer LOG = (Integer) params.getDynValue("LOG");
82
//        if( LOCK_TIMEOUT!=null ) {
83
//            commonParameters.append(";LOG=").append(LOG);
84
//        }
85
//        Integer LOCK_MODE = (Integer) params.getDynValue("LOCK_MODE");
86
//        if( LOCK_TIMEOUT!=null ) {
87
//            commonParameters.append(";LOCK_MODE=").append(LOCK_MODE);
88
//        }
89
        
90
        if( StringUtils.isEmpty(params.getHost()) ) {
91
            // Asumimos que es una conexion directa sobre el filesystem
92
            if( StringUtils.equalsIgnoreCase(FilenameUtils.getExtension(params.getFile().getName()),"zip") ) {
93
                connectionURL =  MessageFormat.format(
94
                    "jdbc:mdb:zip:{0}!/{1}"+commonParameters.toString(),
95
                    dbfilename,
96
                    params.getDBName()
97
                );
98
            } else {
99
                connectionURL =  MessageFormat.format(
100
                    "jdbc:mdb:file:{0}"+commonParameters.toString(),
101
                    dbfilename
102
                );
103
            }
104
        } else if( params.getPort() == null ) {
105
            connectionURL =  MessageFormat.format(
106
                "jdbc:mbd:tcp://{0}/{1}"+commonParameters.toString(),
107
                params.getHost(),
108
                dbfilename
109
            );            
110
        } else {
111
            connectionURL =  MessageFormat.format(                
112
                "jdbc:mdb:tcp://{0}:{1,number,#######}/{2}"+commonParameters.toString(),
113
                params.getHost(),
114
                params.getPort().intValue(),
115
                dbfilename
116
            );
117
        }
118
        LOGGER.debug("connectionURL: {}", connectionURL);
119
        return connectionURL;
120
    }
121

    
122
    public static class ConnectionProvider {
123

    
124
        private static boolean needRegisterDriver = true;
125

    
126
        private BasicDataSource dataSource = null;
127

    
128
        private final MDBConnectionParameters connectionParameters;
129

    
130
//        private static Server server = null;
131
        private static String server = null;
132
        private static boolean startServer = true;
133

    
134
        public ConnectionProvider(MDBConnectionParameters connectionParameters) {
135
            this.connectionParameters = connectionParameters;
136
        }
137
        
138
        public static void stopServer() {
139
          try {
140
//            server.shutdown();
141
          } catch(Throwable th) {
142
            
143
          }
144
          try {
145
//            server.stop();
146
          } catch(Throwable th) {
147
            
148
          }
149
//          server = null;
150
          startServer = true;
151
          LOGGER.info("MDB Server stopped" );
152
        }
153
        
154
        private void startServer() {
155
        
156
            if( startServer && server == null ) {
157
                String port = "9123";
158
//                Server theServer;
159
                String theServer;
160
                String s = System.getProperty("MDBPort");
161
                if( s!=null ) {
162
                    try {
163
                        int n = Integer.parseInt(s);
164
                        port = String.valueOf(n);
165
                    } catch(Throwable th) {
166
                        // Ignore port number, use default.
167
                    }
168
                }
169
                if( System.getProperty("MDBAllowOthers")!=null ) {
170
//                    theServer = Server.createTcpServer("-tcpPort", port, "-tcpAllowOthers", "-ifExists");
171
                } else {
172
//                    theServer = Server.createTcpServer("-tcpPort", port, "-ifExists");
173
                }
174
//                theServer.start();
175
//                server = theServer;
176
                LOGGER.info("MDB Server started" );
177
//                LOGGER.info("  port  :"+ server.getPort());
178
//                LOGGER.info("  URL  :"+ server.getURL());
179
//                LOGGER.info("  status:"+ server.getStatus());
180
                // Tanto si consigue lanzar el server como si no, no lo vuelve a intentar
181
                startServer = false;
182
            }
183

    
184
        }
185

    
186
        @Override
187
        public String toString() {
188
            StringBuilder builder = new StringBuilder();
189
            builder.append(" url=").append(connectionParameters.getUrl());
190
            builder.append(" driver name=").append(connectionParameters.getJDBCDriverClassName());
191
            builder.append(" user=").append(connectionParameters.getUser());
192
            return builder.toString();
193
        }
194
        
195
        public Connection getConnection() throws SQLException {
196
            if (this.dataSource == null) {
197
                this.dataSource = this.createDataSource();               
198
            }
199
            Connection conn = this.dataSource.getConnection();
200
            try {
201
                conn.createStatement().execute("SELECT TOP 1 SRID FROM SPATIAL_REF_SYS");
202
            } catch(SQLException ex) {
203
//                H2GISExtension.load(conn);
204
            }
205
            try {
206
                conn.createStatement().execute("CREATE SCHEMA IF NOT EXISTS PUBLIC;SET SCHEMA PUBLIC");
207
            } catch(SQLException ex) {
208
                // Ignore this error.
209
            }
210

    
211
            return conn;
212
        }
213

    
214
        private BasicDataSource createDataSource() throws SQLException {
215
            if (!this.isRegistered()) {
216
                this.registerDriver();
217
            }
218
            startServer();
219
            MDBConnectionParameters params = connectionParameters;
220

    
221
            BasicDataSource ds = new BasicDataSource();
222
            ds.setDriverClassName(params.getJDBCDriverClassName());
223
            if( !StringUtils.isEmpty(params.getUser()) ) {
224
                ds.setUsername(params.getUser());
225
            }
226
            if( !StringUtils.isEmpty(params.getPassword()) ) {
227
                ds.setPassword(params.getPassword());
228
            }
229
            ds.setUrl(params.getUrl());
230

    
231
            ds.setMaxWait(60L * 1000);
232
            return ds;
233
        }
234

    
235
        private boolean isRegistered() {
236
            return needRegisterDriver;
237
        }
238

    
239
        public void registerDriver() throws SQLException {
240
            String className = this.connectionParameters.getJDBCDriverClassName();
241
            if (className == null) {
242
                return;
243
            }
244
            try {
245
                Class theClass = Class.forName(className);
246
                if (theClass == null) {
247
                    throw new JDBCDriverClassNotFoundException(MDBLibrary.NAME, className);
248
                }
249
            } catch (Exception e) {
250
                throw new SQLException("Can't register JDBC driver '" + className + "'.", e);
251
            }
252
            needRegisterDriver = false;
253
        }
254

    
255
    }
256

    
257
    private ConnectionProvider connectionProvider = null;
258
 
259
    /**
260
     * Constructor for use only for testing purposes.
261
     */
262
    public MDBHelper() { 
263
        super(null);
264
    }
265
  
266
    public MDBHelper(JDBCConnectionParameters connectionParameters) {
267
        super(connectionParameters);
268
        this.srssolver = new SRSSolverBase(this);
269
    }
270

    
271
    @Override
272
    public synchronized Connection  getConnection() throws AccessResourceException {
273
        try {
274
            if (this.connectionProvider == null) {
275
              MDBConnectionParameters connectionParameters = this.getConnectionParameters();
276
              if( connectionParameters==null ) {
277
                return null; // Testing mode?
278
              }
279
              this.connectionProvider = new ConnectionProvider(connectionParameters);
280
            }
281
            Connection connection = this.connectionProvider.getConnection();
282
            if( LOGGER.isDebugEnabled() ) {
283
                LOGGER.debug("getConnection: connection = "+connection.hashCode()+ connectionProvider.toString());
284
            }
285
            return connection;
286
        } catch (SQLException ex) {
287
            throw new AccessResourceException(MDBLibrary.NAME, ex);
288
        }
289
    }
290

    
291
    @Override
292
    public void closeConnection(Connection connection) {
293
      if( connection!=null ) { // In test ???
294
        LOGGER.debug("closeConnection: connection = "+connection.hashCode());
295
      }
296
      super.closeConnection(connection);
297
    }
298
    
299
    @Override
300
    public MDBConnectionParameters getConnectionParameters() {
301
        return (MDBConnectionParameters) super.getConnectionParameters();
302
    }
303
    
304
    @Override
305
    public String getConnectionURL() {
306
        return getConnectionURL(this.getConnectionParameters());
307
    }
308

    
309
    @Override
310
    protected String getResourceType() {
311
        return MDBLibrary.NAME;
312
    }
313

    
314
    @Override
315
    public String getProviderName() {
316
        return MDBLibrary.NAME;
317
    }
318

    
319
    @Override
320
    public JDBCSQLBuilderBase createSQLBuilder() {
321
        return new MDBSQLBuilder(this);
322
    }
323
    
324
    @Override
325
    public OperationsFactory getOperations() {
326
        if (this.operationsFactory == null) {
327
            this.operationsFactory = new MDBOperationsFactory(this);
328
        }
329
        return operationsFactory;
330
    }
331

    
332
    @Override
333
    public GeometrySupportType getGeometrySupportType() {
334
        return GeometrySupportType.WKB;
335
    }
336

    
337
    @Override
338
    public boolean hasSpatialFunctions() {
339
        return true;
340
    }
341

    
342
    @Override
343
    public boolean canWriteGeometry(int geometryType, int geometrySubtype) {
344
        return true;
345
    }
346

    
347
    @Override
348
    public String getQuoteForIdentifiers() {
349
        return "\"";
350
    }
351

    
352
    @Override
353
    public boolean allowAutomaticValues() {
354
        return true;
355
    }
356

    
357
    @Override
358
    public boolean supportOffsetInSelect() {
359
        return true;
360
    }
361

    
362
    @Override
363
    public String getQuoteForStrings() {
364
        return "'";
365
    }
366

    
367
    @Override
368
    public String getSourceId(JDBCStoreParameters parameters) {
369
        return parameters.getDBName() + "." + 
370
               parameters.getSchema()+ "." + 
371
               parameters.getTable();
372
    }
373

    
374
    @Override
375
    public JDBCNewStoreParameters createNewStoreParameters() {
376
        return new MDBNewStoreParameters();
377
    }
378

    
379
    @Override
380
    public JDBCStoreParameters createOpenStoreParameters() {
381
        return new MDBStoreParameters();
382
    }
383

    
384
    @Override
385
    public JDBCServerExplorerParameters createServerExplorerParameters() {
386
        return new MDBExplorerParameters();
387
    }
388

    
389
    @Override
390
    public JDBCServerExplorer createServerExplorer(
391
            JDBCServerExplorerParameters parameters, 
392
            DataServerExplorerProviderServices providerServices
393
        ) throws InitializeException {
394
        
395
        JDBCServerExplorer explorer = new JDBCServerExplorerBase(
396
                parameters, 
397
                providerServices, 
398
                this
399
        );
400
        this.initialize(explorer, parameters, null);
401
        return explorer;
402
    }
403
}