Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.plugin / org.gvsig.h2spatial / org.gvsig.h2spatial.h2gis132 / org.gvsig.h2spatial.h2gis132.provider / src / main / java / org / gvsig / fmap / dal / store / h2 / H2SpatialUtils.java @ 47716

History | View | Annotate | Download (11.1 KB)

1
package org.gvsig.fmap.dal.store.h2;
2

    
3
import java.io.File;
4
import java.sql.Connection;
5
import java.sql.SQLException;
6
import java.text.MessageFormat;
7
import java.util.HashMap;
8
import java.util.Map;
9
import org.apache.commons.codec.binary.Hex;
10
import org.apache.commons.io.FileUtils;
11
import org.apache.commons.io.FilenameUtils;
12
import org.apache.commons.lang3.StringUtils;
13
import org.gvsig.fmap.dal.store.h2.H2SpatialHelper.H2SpatialConnectionProvider;
14
import static org.gvsig.fmap.dal.store.h2.H2SpatialHelper.LOGGER;
15
import org.gvsig.fmap.dal.store.jdbc.JDBCConnectionParameters;
16
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils;
17
import org.gvsig.fmap.dal.store.jdbc2.spi.ConnectionProvider;
18
import org.h2.tools.Server;
19
import org.h2gis.functions.system.H2GISversion;
20

    
21
/**
22
 *
23
 * @author gvSIG Team
24
 */
25
public class H2SpatialUtils {
26
    
27
    private static boolean enable_server = true;
28
    private static Server h2server = null;
29
    private static boolean startServer = true;
30
    private static boolean lastAllowOthers = true;
31
    private static String lastPort = "9123";
32
    private static Map<String,Connection> globalConnections;
33
    
34

    
35
    private static Thread shutdownHook = new Thread("H2_shutdown_hook") {
36
        @Override
37
        public void run() {
38
            server_stop();
39
        }
40
    };
41

    
42
    public static File[] getH2Files(File f) {
43
        if( f==null ) {
44
            return null;
45
        }
46
        String name = removeH2FileNameExtension(f.getName());
47
        File[] files = new File[62];
48
        files[0] = new File(f.getParentFile(), name+".mv.db");
49
        files[1] = new File(f.getParentFile(), name+".trace.db");
50
        for (int i = 2; i < files.length; i++) {
51
            files[i] = new File(f.getParentFile(), name+".mv.db."+(i-1)+".part");
52
        }
53
        return files;
54
    }
55
    
56
    public static boolean existsH2db(File f) {
57
        File[] files = getH2Files(f);
58
        for (File file : files) {
59
            if( file.exists() ) {
60
                return true;
61
            }
62
        }
63
        return false;
64
    }
65
    
66
    public static boolean removeH2db(File f) {
67
        try {
68
            File[] files = getH2Files(f);
69
            for (File file : files) {
70
                if( file.exists() ) {
71
                    FileUtils.delete(file);
72
                }
73
            }
74
        } catch(Throwable t) {
75
            return false;
76
        }
77
        return true;
78
    }
79
    
80
    public static File normalizeH2File(File f) {
81
        if( f==null ) {
82
            return null;
83
        }
84
        f = new File(f.getParentFile(), normalizeH2FileName(f.getName()));
85
        return f;
86
    }
87

    
88
    public static String normalizeH2FileName(String name) {
89
        String s = removeH2FileNameExtension(name);
90
        if( s == null ) {
91
            return null;
92
        }
93
        return s+".mv.db";
94
    }
95
    
96
    public static String removeH2FileNameExtension(String name) {
97
        if( StringUtils.isBlank(name) ) {
98
            return null;
99
        }
100
        if( name.endsWith(".mv.db") ) {
101
            int l = name.length();
102
            return name.substring(0, l-6);
103
        }
104
        if( name.endsWith(".trace.db") ) {
105
            int l = name.length();
106
            return name.substring(0, l-9);
107
        }
108
        return FilenameUtils.removeExtension(name);
109
    }
110

    
111
    public static File getLocalFile(H2SpatialConnectionParameters params) {
112
        String host = params.getHost();
113
        if( !StringUtils.isEmpty(host) ) {
114
          host = host.toLowerCase().trim();
115
          if( !(host.equals("localhost") || host.equals("127.0.0.1")) ) {
116
            return null;
117
          }
118
        }
119
        File f = params.getFile();
120
        return normalizeH2File(f);
121
    }
122
        
123
    public static String getConnectionURL(H2SpatialConnectionParameters params) {
124
        String connectionURL;
125
        String dbfilename = params.getFile().getAbsolutePath().replace("\\","/");
126
        if( dbfilename!=null ) {
127
            dbfilename = H2SpatialUtils.removeH2FileNameExtension(dbfilename);
128
        }
129
        StringBuilder commonParameters = new StringBuilder();
130
        commonParameters.append(";MODE=PostgreSQL");
131
        commonParameters.append(";SCHEMA=PUBLIC");
132
        commonParameters.append(";ALLOW_LITERALS=ALL");
133
        int splitSize = params.getSplitSize();
134
        
135
        if( StringUtils.isEmpty(params.getHost()) ) {
136
            // Asumimos que es una conexion directa sobre el filesystem
137
            if( StringUtils.equalsIgnoreCase(FilenameUtils.getExtension(params.getFile().getName()),"zip") ) {
138
                connectionURL =  MessageFormat.format(
139
                    "jdbc:h2:zip:{0}!/{1}"+commonParameters.toString(),
140
                    dbfilename,
141
                    params.getDBName()
142
                );
143
            } else if( splitSize>0 ) {
144
                connectionURL =  MessageFormat.format(
145
                    "jdbc:h2:split:{1,number,##}:{0}"+commonParameters.toString(),
146
                    dbfilename,
147
                    splitSize
148
                );
149
            } else {
150
                connectionURL =  MessageFormat.format(
151
                    "jdbc:h2:file:{0}"+commonParameters.toString(),
152
                    dbfilename
153
                );
154
            }
155
        } else if( params.getPort() == null ) {
156
            if( splitSize>0 ) {
157
                connectionURL =  MessageFormat.format(
158
                    "jdbc:h2:tcp://{0}/split:{2,number,##}:/{1}"+commonParameters.toString(),
159
                    params.getHost(),
160
                    dbfilename,
161
                    splitSize
162
                );      
163
            } else {
164
                connectionURL =  MessageFormat.format(
165
                    "jdbc:h2:tcp://{0}/{1}"+commonParameters.toString(),
166
                    params.getHost(),
167
                    dbfilename
168
                );      
169
            }
170
        } else if( splitSize>0 ) {
171
            connectionURL =  MessageFormat.format("jdbc:h2:tcp://{0}:{1,number,#######}/split:{3,number,##}:/{2}"+commonParameters.toString(),
172
                params.getHost(),
173
                (int) params.getPort(),
174
                dbfilename,
175
                splitSize
176
            );
177
        } else {
178
            connectionURL =  MessageFormat.format("jdbc:h2:tcp://{0}:{1,number,#######}/{2}"+commonParameters.toString(),
179
                params.getHost(),
180
                (int) params.getPort(),
181
                dbfilename
182
            );
183
        }
184
        LOGGER.debug("connectionURL: {}", connectionURL);
185
        return connectionURL;
186
    }
187
    
188
    public static synchronized void server_stop() {
189
            if (h2server == null) {
190
                LOGGER.info("The H2 server is already stopped.");
191
            } else {
192
                closeGlobalConnections();
193
                LOGGER.info("Stopping the H2 server.");
194
                LOGGER.info("  port  :" + h2server.getPort());
195
                LOGGER.info("  URL   :" + h2server.getURL());
196
                LOGGER.info("  shutdown server...");
197
                try {
198
                    h2server.shutdown();
199
                } catch (Throwable th) {
200
                    LOGGER.warn("Problems shutdown the H2 server.", th);
201
                }
202
                LOGGER.info("  Stoping server...");
203
                try {
204
                    h2server.stop();
205
                } catch (Throwable th) {
206
                    LOGGER.warn("Problems stopping the H2 server.", th);
207
                }
208
                LOGGER.info("  status:" + h2server.getStatus());
209
                h2server = null;
210
                LOGGER.info("H2 Server stopped");
211
            }
212
            startServer = true;
213
    }
214
    
215
    public static void server_start() {
216
        server_start(lastPort, lastAllowOthers);
217
    }
218
    
219
    public static synchronized void server_start(String port, Boolean allowOthers) {
220
            if( !enable_server ) {
221
                return;
222
            }
223
            if( startServer && h2server == null ) {
224
                if( StringUtils.isBlank(port) ) {
225
                    port = lastPort;
226
                }
227
                if( allowOthers==null ) {
228
                    allowOthers = lastAllowOthers;
229
                }
230
                try {
231
                    Server theH2Server;
232
                    if( allowOthers) {
233
                        theH2Server = Server.createTcpServer("-tcpPort", port, "-ifExists", "-tcpAllowOthers");
234
                    } else {
235
                        theH2Server = Server.createTcpServer("-tcpPort", port, "-ifExists");
236
                    }
237
                    theH2Server.start();
238
                    h2server = theH2Server;
239
                    LOGGER.info("H2 Server started" );
240
                    LOGGER.info("  Engine version : h2 "+ org.h2.engine.Constants.getFullVersion()+", h2gis "+H2GISversion.geth2gisVersion());
241
                    LOGGER.info("  Connection url : jdbc:h2:"+h2server.getURL()+"/ABSOLUTE_DATABASE_PATH;MODE=PostgreSQL;SCHEMA=PUBLIC;ALLOW_LITERALS=ALL");
242
                    LOGGER.info("  status:"+ h2server.getStatus());
243
                    Runtime.getRuntime().removeShutdownHook(shutdownHook);
244
                    Runtime.getRuntime().addShutdownHook(shutdownHook);
245
                    lastPort = port;
246
                    lastAllowOthers = allowOthers;
247
                } catch (SQLException ex) {
248
                    LOGGER.warn("H2 Server not started",ex);
249
                }
250
                // Tanto si consigue lanzar el server como si no, no lo vuelve a intentar
251
                startServer = false;
252
            }
253
    }
254
    
255
    public static void set_enable_server(boolean enable) {
256
        enable_server = enable;
257
    }
258
    
259
    public static void set_server_port(int port) {
260
        lastPort = Integer.toString(port);
261
    }
262
    
263
    public static boolean is_enable_server() {
264
        return enable_server;
265
    }
266
    
267
    public static synchronized boolean is_server_started() {
268
        return h2server!=null;
269
    }
270
    
271
    public static synchronized void addGlobalConnection(H2SpatialConnectionProvider connectionProvider) throws SQLException {
272
        if( globalConnections==null ) {
273
            globalConnections = new HashMap<>();
274
        }
275
        H2SpatialConnectionParameters connectionParameters = connectionProvider.getConnectionParameters();
276
        if( !connectionParameters.getMaintainGlobalConnection() ) {
277
            return;
278
        }
279
        String connectionProviderKey = getConnectionProviderKey(connectionParameters);
280
        Connection x = globalConnections.get(connectionProviderKey);
281
        if( x != null ) {
282
            return;
283
        }
284
        x = connectionProvider.getConnection();
285
        globalConnections.put(connectionProviderKey, x);
286
    }
287
    
288
    public static String getConnectionProviderKey(JDBCConnectionParameters connectionParameters) {
289
        String pass = Hex.encodeHexString((connectionParameters.getPassword()+"").getBytes());
290
//        String pass = connectionParameters.getPassword();
291
        return connectionParameters.getUrl() + ";user:"+connectionParameters.getUser()+"@"+pass;
292
    }    
293
    
294
    public static synchronized void closeGlobalConnections() {
295
        if( globalConnections==null ) {
296
            return;
297
        }
298
        for (Connection conn : globalConnections.values()) {
299
            LOGGER.info("Clossing connection "+ JDBCUtils.getConnId(conn));
300
            JDBCUtils.closeQuietly(conn);
301
        }
302
        globalConnections = null;
303
    }
304
}