/[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 1292 - (hide annotations)
Mon Nov 22 10:39: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: 12226 byte(s)
Reorgnaized ServerList classes in schmitzm a bit
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     import org.apache.commons.lang.ArrayUtils;
12 alfonx 1163 import org.apache.commons.lang.StringUtils;
13 alfonx 1195 import org.apache.log4j.Logger;
14 alfonx 1161 import org.geotools.data.postgis.PostgisNGDataStoreFactory;
15     import org.geotools.jdbc.JDBCDataStore;
16     import org.geotools.jdbc.JDBCDataStoreFactory;
17 alfonx 1163 import org.jfree.util.Log;
18 alfonx 1161
19     import schmitzm.swing.BooleanInputOption;
20     import schmitzm.swing.ManualInputOption;
21     import schmitzm.swing.ManualInputOption.Integer;
22     import schmitzm.swing.ManualInputOption.PasswordViewable;
23     import schmitzm.swing.ManualInputOption.Text;
24     import schmitzm.swing.MultipleOptionPane;
25     import schmitzm.swing.SelectionInputOption;
26     import schmitzm.swing.SelectionInputOption.Combo;
27 alfonx 1195 import skrueger.db.PGUtil;
28 alfonx 1161
29     /**
30     * This class describes all settings needed to connect to a WFS server. This
31     * class extends a {@link HashMap} and contains two groups of keys:<br/>
32     * The first group of keys, are all keys provided by Geotools to create a WFS
33     * datastore, like: {@link JDBCDataStore#SCHEMA} .<br/>
34     * The second group are additional keys defined in the enum
35     * {@link DbServerSettings.Key}.<br/>
36     * This class can serialize all important parameters needed to define the
37     * connection into a {@link String} with {@link #toPropertiesString()} and
38     * re-import the String with {@link #parsePropertiesString(String)}.
39     */
40 alfonx 1164 public class DbServerSettings extends ServerSettings<Object, Object> {
41 alfonx 1161
42 alfonx 1195 Logger log = Logger.getLogger(DbServerSettings.class);
43    
44 alfonx 1164 public enum DbType {
45     postgis("postgresql");
46    
47     private final String protocolString;
48    
49     DbType(String protocolString) {
50     this.protocolString = protocolString;
51     }
52    
53     public String getProtocolString() {
54     return protocolString;
55     };
56     }
57    
58 alfonx 1161 /**
59     * params.put(JDBCDataStoreFactory.DBTYPE.key, "postgis");
60     * params.put(JDBCDataStoreFactory.HOST.key, host); // the name or ip
61     * params.put(JDBCDataStoreFactory.PORT.key, port); // the port that
62     *
63     * params.put(JDBCDataStoreFactory.DATABASE.key, database); // the
64     *
65     * // name params.put(JDBCDataStoreFactory.USER.key, username); // the user
66     * to params.put(JDBCDataStoreFactory.PASSWD.key, password); // the
67     *
68     * params.put(JDBCDataStoreFactory.SCHEMA, schema);
69     *
70     * params.put(JDBCDataStoreFactory.EXPOSE_PK.key, true); *
71     */
72    
73     public enum Key {
74     }
75    
76 alfonx 1195 private static Connection dbc;
77    
78 alfonx 1164 /**
79     * Opens a GUI that asks the use define a DB connection.
80     *
81     * @param dbServer
82     * <code>null</code> to create a new instance, or an instance to
83     * edit.
84     * @return <code>null</code> if the user cancelled the creation of a new
85     * {@link DbServerSettings}, otherwise the edited instance.
86     */
87     public static DbServerSettings createOrEdit(Component owner,
88     DbServerSettings dbServer) {
89     boolean newCreated = false;
90 alfonx 1161
91 alfonx 1164 if (dbServer == null) {
92     newCreated = true;
93     dbServer = new DbServerSettings(DbType.postgis);
94     }
95 alfonx 1161
96 alfonx 1164 Combo<DbType> dpTypeInput = new SelectionInputOption.Combo<DbType>(
97     "Database type", true, DbType.values(), ArrayUtils.indexOf(
98     DbType.values(), dbServer.getDbType()), DbType.values());
99    
100     Text hostInput = new ManualInputOption.Text("Hostname", true,
101     dbServer.getHost());
102    
103     Integer portInput = new ManualInputOption.Integer("Port", true,
104     dbServer.getPort());
105    
106     Text databaseInput = new ManualInputOption.Text("Database", true,
107     dbServer.getDatabase());
108    
109     Text schemaInput = new ManualInputOption.Text("Schema", true,
110     dbServer.getSchema());
111    
112     Text userInput = new ManualInputOption.Text("Username", true,
113     dbServer.getUsername());
114    
115     PasswordViewable passwdInput = new ManualInputOption.PasswordViewable(
116     "Password", true, dbServer.getPassword());
117    
118     BooleanInputOption exposePkInput = new BooleanInputOption(
119     "Expose primary keys", dbServer.getExposePrimaryKey());
120    
121     Object[] input = MultipleOptionPane.showMultipleInputDialog(owner,
122     "DB Connection paramters", dpTypeInput, hostInput, portInput,
123     databaseInput, schemaInput, userInput, passwdInput,
124     exposePkInput);
125    
126     if (input == null) {
127     if (newCreated)
128     return null;
129     else
130     return dbServer;
131     } else {
132     dbServer.setDbType((DbType) input[0]);
133     dbServer.setHost((String) input[1]);
134     dbServer.setPort((java.lang.Integer) input[2]);
135     dbServer.setDatabase((String) input[3]);
136     dbServer.setSchema((String) input[4]);
137     dbServer.setUsername((String) input[5]);
138     dbServer.setPassword(String.valueOf((char[]) input[6]));
139     dbServer.setExposePrimaryKey((Boolean) input[7]);
140 alfonx 1161 }
141    
142 alfonx 1164 return dbServer;
143    
144 alfonx 1161 }
145    
146 alfonx 1164 /**
147     * @return transforms the settings to a String that can be stored in a
148     * .properties line. @see #parsePropertiesString
149     * @throws MalformedURLException
150     */
151 alfonx 1291 @Override
152 alfonx 1292 public boolean parsePropertiesString(String propString)
153 alfonx 1164 throws MalformedURLException {
154    
155     if (propString == null || propString.isEmpty())
156     throw new IllegalArgumentException("parameter to parse was empty");
157     try {
158    
159     String[] split = propString.split(Pattern.quote(DELIMITER));
160    
161     int i = 0;
162 alfonx 1292 setDbType( DbType.valueOf(split[i++]));
163     // DbServerSettings dbServer = new DbServerSettings(
164     // DbType.valueOf(split[i++])
165     // );
166 alfonx 1164
167 alfonx 1292 setTitle(split[i++]);
168     setHost(split[i++]);
169     setPort(java.lang.Integer.valueOf(split[i++]));
170     setUsername(StringUtils.stripToNull(split[i++]));
171     setPassword(split[i++]);
172     setDatabase(split[i++]);
173     setExposePrimaryKey(Boolean.valueOf(split[i++]));
174     setSchema(stringOrNull(split[i++]));
175 alfonx 1164
176 alfonx 1292 return true;
177 alfonx 1164 } catch (Exception e) {
178     Log.warn("couldn't parse " + propString, e);
179 alfonx 1292 return false;
180 alfonx 1164 }
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