/[schmitzm]/branches/2.4.x/src/skrueger/geotools/io/GtDbServerSettings.java
ViewVC logotype

Annotation of /branches/2.4.x/src/skrueger/geotools/io/GtDbServerSettings.java

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1291 - (hide annotations)
Mon Nov 22 01:18:13 2010 UTC (14 years, 3 months ago) by alfonx
Original Path: trunk/src/skrueger/geotools/io/DbServerSettings.java
File MIME type: text/plain
File size: 12303 byte(s)
Preparing GP export to GS
1 alfonx 1161 package skrueger.geotools.io;
2    
3     import java.awt.Component;
4     import java.net.MalformedURLException;
5 alfonx 1195 import java.sql.Connection;
6     import java.sql.DriverManager;
7     import java.sql.SQLException;
8 alfonx 1161 import java.util.HashMap;
9     import java.util.regex.Pattern;
10    
11 alfonx 1291 import javax.management.RuntimeErrorException;
12    
13 alfonx 1161 import org.apache.commons.lang.ArrayUtils;
14 alfonx 1163 import org.apache.commons.lang.StringUtils;
15 alfonx 1195 import org.apache.log4j.Logger;
16 alfonx 1161 import org.geotools.data.postgis.PostgisNGDataStoreFactory;
17     import org.geotools.jdbc.JDBCDataStore;
18     import org.geotools.jdbc.JDBCDataStoreFactory;
19 alfonx 1163 import org.jfree.util.Log;
20 alfonx 1161
21     import schmitzm.swing.BooleanInputOption;
22     import schmitzm.swing.ManualInputOption;
23     import schmitzm.swing.ManualInputOption.Integer;
24     import schmitzm.swing.ManualInputOption.PasswordViewable;
25     import schmitzm.swing.ManualInputOption.Text;
26     import schmitzm.swing.MultipleOptionPane;
27     import schmitzm.swing.SelectionInputOption;
28     import schmitzm.swing.SelectionInputOption.Combo;
29 alfonx 1195 import skrueger.db.PGUtil;
30 alfonx 1161
31     /**
32     * This class describes all settings needed to connect to a WFS server. This
33     * class extends a {@link HashMap} and contains two groups of keys:<br/>
34     * The first group of keys, are all keys provided by Geotools to create a WFS
35     * datastore, like: {@link JDBCDataStore#SCHEMA} .<br/>
36     * The second group are additional keys defined in the enum
37     * {@link DbServerSettings.Key}.<br/>
38     * This class can serialize all important parameters needed to define the
39     * connection into a {@link String} with {@link #toPropertiesString()} and
40     * re-import the String with {@link #parsePropertiesString(String)}.
41     */
42 alfonx 1164 public class DbServerSettings extends ServerSettings<Object, Object> {
43 alfonx 1161
44 alfonx 1195 Logger log = Logger.getLogger(DbServerSettings.class);
45    
46 alfonx 1164 public enum DbType {
47     postgis("postgresql");
48    
49     private final String protocolString;
50    
51     DbType(String protocolString) {
52     this.protocolString = protocolString;
53     }
54    
55     public String getProtocolString() {
56     return protocolString;
57     };
58     }
59    
60 alfonx 1161 /**
61     * params.put(JDBCDataStoreFactory.DBTYPE.key, "postgis");
62     * params.put(JDBCDataStoreFactory.HOST.key, host); // the name or ip
63     * params.put(JDBCDataStoreFactory.PORT.key, port); // the port that
64     *
65     * params.put(JDBCDataStoreFactory.DATABASE.key, database); // the
66     *
67     * // name params.put(JDBCDataStoreFactory.USER.key, username); // the user
68     * to params.put(JDBCDataStoreFactory.PASSWD.key, password); // the
69     *
70     * params.put(JDBCDataStoreFactory.SCHEMA, schema);
71     *
72     * params.put(JDBCDataStoreFactory.EXPOSE_PK.key, true); *
73     */
74    
75     public enum Key {
76     }
77    
78 alfonx 1195 private static Connection dbc;
79    
80 alfonx 1164 /**
81     * Opens a GUI that asks the use define a DB connection.
82     *
83     * @param dbServer
84     * <code>null</code> to create a new instance, or an instance to
85     * edit.
86     * @return <code>null</code> if the user cancelled the creation of a new
87     * {@link DbServerSettings}, otherwise the edited instance.
88     */
89     public static DbServerSettings createOrEdit(Component owner,
90     DbServerSettings dbServer) {
91     boolean newCreated = false;
92 alfonx 1161
93 alfonx 1164 if (dbServer == null) {
94     newCreated = true;
95     dbServer = new DbServerSettings(DbType.postgis);
96     }
97 alfonx 1161
98 alfonx 1164 Combo<DbType> dpTypeInput = new SelectionInputOption.Combo<DbType>(
99     "Database type", true, DbType.values(), ArrayUtils.indexOf(
100     DbType.values(), dbServer.getDbType()), DbType.values());
101    
102     Text hostInput = new ManualInputOption.Text("Hostname", true,
103     dbServer.getHost());
104    
105     Integer portInput = new ManualInputOption.Integer("Port", true,
106     dbServer.getPort());
107    
108     Text databaseInput = new ManualInputOption.Text("Database", true,
109     dbServer.getDatabase());
110    
111     Text schemaInput = new ManualInputOption.Text("Schema", true,
112     dbServer.getSchema());
113    
114     Text userInput = new ManualInputOption.Text("Username", true,
115     dbServer.getUsername());
116    
117     PasswordViewable passwdInput = new ManualInputOption.PasswordViewable(
118     "Password", true, dbServer.getPassword());
119    
120     BooleanInputOption exposePkInput = new BooleanInputOption(
121     "Expose primary keys", dbServer.getExposePrimaryKey());
122    
123     Object[] input = MultipleOptionPane.showMultipleInputDialog(owner,
124     "DB Connection paramters", dpTypeInput, hostInput, portInput,
125     databaseInput, schemaInput, userInput, passwdInput,
126     exposePkInput);
127    
128     if (input == null) {
129     if (newCreated)
130     return null;
131     else
132     return dbServer;
133     } else {
134     dbServer.setDbType((DbType) input[0]);
135     dbServer.setHost((String) input[1]);
136     dbServer.setPort((java.lang.Integer) input[2]);
137     dbServer.setDatabase((String) input[3]);
138     dbServer.setSchema((String) input[4]);
139     dbServer.setUsername((String) input[5]);
140     dbServer.setPassword(String.valueOf((char[]) input[6]));
141     dbServer.setExposePrimaryKey((Boolean) input[7]);
142 alfonx 1161 }
143    
144 alfonx 1164 return dbServer;
145    
146 alfonx 1161 }
147    
148 alfonx 1164 /**
149     * @return transforms the settings to a String that can be stored in a
150     * .properties line. @see #parsePropertiesString
151     * @throws MalformedURLException
152     */
153 alfonx 1291 @Override
154     public DbServerSettings parsePropertiesString(String propString)
155 alfonx 1164 throws MalformedURLException {
156    
157     if (propString == null || propString.isEmpty())
158     throw new IllegalArgumentException("parameter to parse was empty");
159     try {
160    
161     String[] split = propString.split(Pattern.quote(DELIMITER));
162    
163     int i = 0;
164     DbServerSettings dbServer = new DbServerSettings(
165     DbType.valueOf(split[i++]));
166    
167     dbServer.setTitle(split[i++]);
168     dbServer.setHost(split[i++]);
169     dbServer.setPort(java.lang.Integer.valueOf(split[i++]));
170     dbServer.setUsername(StringUtils.stripToNull(split[i++]));
171     dbServer.setPassword(split[i++]);
172     dbServer.setDatabase(split[i++]);
173     dbServer.setExposePrimaryKey(Boolean.valueOf(split[i++]));
174     dbServer.setSchema(stringOrNull(split[i++]));
175    
176     return dbServer;
177     } catch (Exception e) {
178     Log.warn("couldn't parse " + propString, e);
179     return null;
180     }
181 alfonx 1161 }
182    
183 alfonx 1164 private String[] cachedTypeNames = null;
184 alfonx 1195 private String[] cachedGeometryTableNames;
185 alfonx 1164
186     public DbServerSettings() {
187 alfonx 1165 this(DbType.postgis);
188 alfonx 1291
189 alfonx 1161 }
190    
191 alfonx 1164 public DbServerSettings(DbType dbType) {
192     setDbType(dbType);
193     setHost("localhost");
194     setSchema("public");
195 alfonx 1165 put(JDBCDataStoreFactory.PK_METADATA_TABLE.key, null);
196 alfonx 1161 }
197    
198 alfonx 1291 public DbServerSettings(String propertiesString) {
199     try {
200     parsePropertiesString(propertiesString);
201     } catch (MalformedURLException e) {
202     throw new RuntimeException(e);
203     }
204     }
205    
206 alfonx 1164 public String[] getCachedTypeNames() {
207     return cachedTypeNames;
208 alfonx 1161 }
209    
210 alfonx 1164 public String getDatabase() {
211     return (String) get(JDBCDataStoreFactory.DATABASE.key);
212 alfonx 1161 }
213    
214 alfonx 1164 public DbType getDbType() {
215     String dbt = (String) get(PostgisNGDataStoreFactory.DBTYPE.key);
216     if (dbt != null)
217     return DbType.valueOf(dbt);
218     return null;
219     }
220    
221 alfonx 1161 public Boolean getExposePrimaryKey() {
222     Boolean expk = (Boolean) get(JDBCDataStoreFactory.EXPOSE_PK.key);
223     if (expk == null)
224     return (Boolean) JDBCDataStoreFactory.EXPOSE_PK.sample;
225     return expk;
226     }
227    
228     public String getHost() {
229     return (String) get(JDBCDataStoreFactory.HOST.key);
230     }
231    
232     public String getPassword() {
233     return (String) get(JDBCDataStoreFactory.PASSWD.key);
234     }
235    
236 alfonx 1164 public java.lang.Integer getPort() {
237     java.lang.Integer port = (java.lang.Integer) get(JDBCDataStoreFactory.PORT.key);
238     if (port == null)
239     return (java.lang.Integer) JDBCDataStoreFactory.PORT.sample;
240     return port;
241 alfonx 1161 }
242    
243 alfonx 1164 public String getSchema() {
244     return (String) get(JDBCDataStoreFactory.SCHEMA.key);
245     }
246    
247 alfonx 1161 public String getUsername() {
248     return (String) get(JDBCDataStoreFactory.USER.key);
249     }
250    
251 alfonx 1164 /**
252     * @return <code>true</code>, if all parameters look OK, without actually
253     * opening any connection.
254     */
255     public boolean isWellDefined() {
256     if (getDbType() == null)
257     return false;
258    
259     if (getHost() == null)
260     return false;
261    
262     if (getUsername() == null)
263     return false;
264    
265     if (getPassword() == null)
266     return false;
267    
268     if (getPort() == null)
269     return false;
270    
271     if (getSchema() == null)
272     return false;
273    
274     return true;
275 alfonx 1161 }
276    
277 alfonx 1164 public void setCachedTypeNames(String[] cachedTypeNames) {
278     this.cachedTypeNames = cachedTypeNames;
279 alfonx 1161 }
280    
281 alfonx 1164 public void setDatabase(String db) {
282     put(JDBCDataStoreFactory.DATABASE.key, db);
283 alfonx 1161 }
284    
285     public void setDbType(DbType dbType) {
286     put(PostgisNGDataStoreFactory.DBTYPE.key, dbType.toString());
287    
288     if (dbType == DbType.postgis) {
289     if (getPort() == null) {
290     // For a PostGIS DBMS automatically set the port to 5432
291     setPort(5432);
292     }
293     if (getUsername() == null) {
294     // For a PostGIS DBMS automatically set the user to postgres
295     setUsername("postgres");
296     }
297    
298     }
299    
300     }
301    
302 alfonx 1164 public void setExposePrimaryKey(Boolean exportPk) {
303     put(JDBCDataStoreFactory.EXPOSE_PK.key, exportPk);
304 alfonx 1161 }
305    
306 alfonx 1164 public void setHost(String host) {
307     put(JDBCDataStoreFactory.HOST.key, host);
308 alfonx 1161 }
309    
310 alfonx 1164 public void setPassword(String password) {
311     put(JDBCDataStoreFactory.PASSWD.key, password);
312     }
313 alfonx 1161
314 alfonx 1164 public void setPort(java.lang.Integer port) {
315     put(JDBCDataStoreFactory.PORT.key, port);
316     }
317 alfonx 1161
318 alfonx 1164 public void setSchema(String schema) {
319     put(JDBCDataStoreFactory.SCHEMA.key, schema);
320     }
321 alfonx 1161
322 alfonx 1164 public void setUsername(String username) {
323     put(JDBCDataStoreFactory.USER.key, username);
324 alfonx 1161 }
325    
326     /**
327     * @return transforms the settings to a String that can be stored in a
328     * .properties line. @see #parsePropertiesString
329     */
330     public String toPropertiesString() {
331    
332     StringBuffer serialized = new StringBuffer(100);
333    
334     serialized.append(getDbType().toString());
335     serialized.append(DELIMITER);
336    
337 alfonx 1164 serialized.append(getTitle());
338     serialized.append(DELIMITER);
339 alfonx 1165
340 alfonx 1162 serialized.append(getHost());
341 alfonx 1161 serialized.append(DELIMITER);
342    
343     serialized.append(getPort().toString());
344     serialized.append(DELIMITER);
345    
346 alfonx 1162 serialized.append(getUsername());
347 alfonx 1161 serialized.append(DELIMITER);
348    
349 alfonx 1162 serialized.append(getPassword());
350 alfonx 1161 serialized.append(DELIMITER);
351    
352 alfonx 1162 serialized.append(getDatabase());
353 alfonx 1161 serialized.append(DELIMITER);
354    
355     serialized.append(getExposePrimaryKey().toString());
356     serialized.append(DELIMITER);
357    
358     serialized.append(getSchema().toString());
359 alfonx 1164 // serialized.append(DELIMITER);
360 alfonx 1161
361     return serialized.toString();
362     }
363    
364     @Override
365     public String toString() {
366    
367     StringBuffer s = new StringBuffer();
368    
369     if (getDbType() != null) {
370     s.append(getDbType().getProtocolString() + "://");
371     }
372    
373     s.append(getHost());
374    
375 alfonx 1163 if (getPort() != null && getPort() != 5432) {
376 alfonx 1161 s.append(":" + getPort());
377     }
378    
379     s.append("/" + getDatabase());
380    
381     return s.toString();
382     }
383 alfonx 1195
384     /**
385     * returns a valid Connection to our postgresql Database. Name of database,
386     * username and password must be provided.
387     *
388     * @param database
389     * name of the database
390     * @param username
391     * a valid username
392     * @param password
393     * valid password
394     * @return database connection
395     * @throws SQLException
396     * @throws ClassNotFoundException
397     */
398     public Connection getDatabaseConnection() {
399    
400     try {
401    
402     if (dbc == null || dbc.isClosed()) {
403     dbc = createNewDatabaseConnection();
404     }
405     return dbc;
406     } catch (Exception e) {
407     return null;
408     }
409     }
410    
411     private Connection createNewDatabaseConnection() throws SQLException {
412     try {
413     Class.forName("org.postgresql.Driver");
414     } catch (ClassNotFoundException e) {
415     throw new RuntimeException(e);
416     }
417     String url = "jdbc:postgresql://" + getHost()
418     // + (":" + PropertyUtils.getDbPort())
419     + ("/" + getDatabase());
420    
421     String password = getPassword();
422     String username = getUsername();
423    
424     // log.debug("DB URL: " + url + " u=" + username + " p="
425     // + password);
426    
427     return DriverManager.getConnection(url, username, password);
428     }
429    
430     public String[] getDescribedTablesWithGeometry() {
431    
432     if (cachedGeometryTableNames == null) {
433    
434     Connection dc;
435     try {
436     dc = createNewDatabaseConnection();
437     try {
438    
439     cachedGeometryTableNames = PGUtil
440     .getColumnsDescribedInGeometryColumnsTable(dc
441     .createStatement());
442    
443     } catch (SQLException e) {
444     log.error(e, e);
445     } finally {
446     dc.close();
447     }
448     } catch (SQLException e1) {
449     log.error(e1, e1);
450     return new String[0];
451     }
452     }
453     return cachedGeometryTableNames;
454     }
455    
456     @Override
457     protected void finalize() throws Throwable {
458     super.finalize();
459     dispose();
460     }
461    
462     public void dispose() {
463     try {
464     if (dbc != null && !dbc.isClosed()) {
465     dbc.close();
466     dbc = null;
467     }
468     } catch (SQLException e) {
469     log.error("Error while disposing the database connection to "
470     + toString(), e);
471     }
472     }
473     }

Properties

Name Value
svn:eol-style native
svn:keywords Id URL
svn:mime-type text/plain

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26