/[schmitzm]/branches/2.3.x/src/skrueger/geotools/io/DbServerSettings.java
ViewVC logotype

Contents of /branches/2.3.x/src/skrueger/geotools/io/DbServerSettings.java

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1240 - (show annotations)
Fri Nov 5 13:02:30 2010 UTC (14 years, 3 months ago) by alfonx
File MIME type: text/plain
File size: 12064 byte(s)
Branch 2.3.x angelegt

1 package skrueger.geotools.io;
2
3 import java.awt.Component;
4 import java.net.MalformedURLException;
5 import java.sql.Connection;
6 import java.sql.DriverManager;
7 import java.sql.SQLException;
8 import java.util.HashMap;
9 import java.util.regex.Pattern;
10
11 import org.apache.commons.lang.ArrayUtils;
12 import org.apache.commons.lang.StringUtils;
13 import org.apache.log4j.Logger;
14 import org.geotools.data.postgis.PostgisNGDataStoreFactory;
15 import org.geotools.jdbc.JDBCDataStore;
16 import org.geotools.jdbc.JDBCDataStoreFactory;
17 import org.jfree.util.Log;
18
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 import skrueger.db.PGUtil;
28
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 public class DbServerSettings extends ServerSettings<Object, Object> {
41
42 Logger log = Logger.getLogger(DbServerSettings.class);
43
44 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 /**
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 private static Connection dbc;
77
78 /**
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
91 if (dbServer == null) {
92 newCreated = true;
93 dbServer = new DbServerSettings(DbType.postgis);
94 }
95
96 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 }
141
142 return dbServer;
143
144 }
145
146 /**
147 * @return transforms the settings to a String that can be stored in a
148 * .properties line. @see #parsePropertiesString
149 * @throws MalformedURLException
150 */
151 public static DbServerSettings parsePropertiesString(String propString)
152 throws MalformedURLException {
153
154 if (propString == null || propString.isEmpty())
155 throw new IllegalArgumentException("parameter to parse was empty");
156 try {
157
158 String[] split = propString.split(Pattern.quote(DELIMITER));
159
160 int i = 0;
161 DbServerSettings dbServer = new DbServerSettings(
162 DbType.valueOf(split[i++]));
163
164 dbServer.setTitle(split[i++]);
165 dbServer.setHost(split[i++]);
166 dbServer.setPort(java.lang.Integer.valueOf(split[i++]));
167 dbServer.setUsername(StringUtils.stripToNull(split[i++]));
168 dbServer.setPassword(split[i++]);
169 dbServer.setDatabase(split[i++]);
170 dbServer.setExposePrimaryKey(Boolean.valueOf(split[i++]));
171 dbServer.setSchema(stringOrNull(split[i++]));
172
173 return dbServer;
174 } catch (Exception e) {
175 Log.warn("couldn't parse " + propString, e);
176 return null;
177 }
178 }
179
180 private String[] cachedTypeNames = null;
181 private String[] cachedGeometryTableNames;
182
183 public DbServerSettings() {
184 this(DbType.postgis);
185 }
186
187 public DbServerSettings(DbType dbType) {
188 setDbType(dbType);
189 setHost("localhost");
190 setSchema("public");
191 put(JDBCDataStoreFactory.PK_METADATA_TABLE.key, null);
192 }
193
194 public String[] getCachedTypeNames() {
195 return cachedTypeNames;
196 }
197
198 public String getDatabase() {
199 return (String) get(JDBCDataStoreFactory.DATABASE.key);
200 }
201
202 public DbType getDbType() {
203 String dbt = (String) get(PostgisNGDataStoreFactory.DBTYPE.key);
204 if (dbt != null)
205 return DbType.valueOf(dbt);
206 return null;
207 }
208
209 public Boolean getExposePrimaryKey() {
210 Boolean expk = (Boolean) get(JDBCDataStoreFactory.EXPOSE_PK.key);
211 if (expk == null)
212 return (Boolean) JDBCDataStoreFactory.EXPOSE_PK.sample;
213 return expk;
214 }
215
216 public String getHost() {
217 return (String) get(JDBCDataStoreFactory.HOST.key);
218 }
219
220 public String getPassword() {
221 return (String) get(JDBCDataStoreFactory.PASSWD.key);
222 }
223
224 public java.lang.Integer getPort() {
225 java.lang.Integer port = (java.lang.Integer) get(JDBCDataStoreFactory.PORT.key);
226 if (port == null)
227 return (java.lang.Integer) JDBCDataStoreFactory.PORT.sample;
228 return port;
229 }
230
231 public String getSchema() {
232 return (String) get(JDBCDataStoreFactory.SCHEMA.key);
233 }
234
235 public String getUsername() {
236 return (String) get(JDBCDataStoreFactory.USER.key);
237 }
238
239 /**
240 * @return <code>true</code>, if all parameters look OK, without actually
241 * opening any connection.
242 */
243 public boolean isWellDefined() {
244 if (getDbType() == null)
245 return false;
246
247 if (getHost() == null)
248 return false;
249
250 if (getUsername() == null)
251 return false;
252
253 if (getPassword() == null)
254 return false;
255
256 if (getPort() == null)
257 return false;
258
259 if (getSchema() == null)
260 return false;
261
262 return true;
263 }
264
265 public void setCachedTypeNames(String[] cachedTypeNames) {
266 this.cachedTypeNames = cachedTypeNames;
267 }
268
269 public void setDatabase(String db) {
270 put(JDBCDataStoreFactory.DATABASE.key, db);
271 }
272
273 public void setDbType(DbType dbType) {
274 put(PostgisNGDataStoreFactory.DBTYPE.key, dbType.toString());
275
276 if (dbType == DbType.postgis) {
277 if (getPort() == null) {
278 // For a PostGIS DBMS automatically set the port to 5432
279 setPort(5432);
280 }
281 if (getUsername() == null) {
282 // For a PostGIS DBMS automatically set the user to postgres
283 setUsername("postgres");
284 }
285
286 }
287
288 }
289
290 public void setExposePrimaryKey(Boolean exportPk) {
291 put(JDBCDataStoreFactory.EXPOSE_PK.key, exportPk);
292 }
293
294 public void setHost(String host) {
295 put(JDBCDataStoreFactory.HOST.key, host);
296 }
297
298 public void setPassword(String password) {
299 put(JDBCDataStoreFactory.PASSWD.key, password);
300 }
301
302 public void setPort(java.lang.Integer port) {
303 put(JDBCDataStoreFactory.PORT.key, port);
304 }
305
306 public void setSchema(String schema) {
307 put(JDBCDataStoreFactory.SCHEMA.key, schema);
308 }
309
310 public void setUsername(String username) {
311 put(JDBCDataStoreFactory.USER.key, username);
312 }
313
314 /**
315 * @return transforms the settings to a String that can be stored in a
316 * .properties line. @see #parsePropertiesString
317 */
318 public String toPropertiesString() {
319
320 StringBuffer serialized = new StringBuffer(100);
321
322 serialized.append(getDbType().toString());
323 serialized.append(DELIMITER);
324
325 serialized.append(getTitle());
326 serialized.append(DELIMITER);
327
328 serialized.append(getHost());
329 serialized.append(DELIMITER);
330
331 serialized.append(getPort().toString());
332 serialized.append(DELIMITER);
333
334 serialized.append(getUsername());
335 serialized.append(DELIMITER);
336
337 serialized.append(getPassword());
338 serialized.append(DELIMITER);
339
340 serialized.append(getDatabase());
341 serialized.append(DELIMITER);
342
343 serialized.append(getExposePrimaryKey().toString());
344 serialized.append(DELIMITER);
345
346 serialized.append(getSchema().toString());
347 // serialized.append(DELIMITER);
348
349 return serialized.toString();
350 }
351
352 @Override
353 public String toString() {
354
355 StringBuffer s = new StringBuffer();
356
357 if (getDbType() != null) {
358 s.append(getDbType().getProtocolString() + "://");
359 }
360
361 s.append(getHost());
362
363 if (getPort() != null && getPort() != 5432) {
364 s.append(":" + getPort());
365 }
366
367 s.append("/" + getDatabase());
368
369 return s.toString();
370 }
371
372 /**
373 * returns a valid Connection to our postgresql Database. Name of database,
374 * username and password must be provided.
375 *
376 * @param database
377 * name of the database
378 * @param username
379 * a valid username
380 * @param password
381 * valid password
382 * @return database connection
383 * @throws SQLException
384 * @throws ClassNotFoundException
385 */
386 public Connection getDatabaseConnection() {
387
388 try {
389
390 if (dbc == null || dbc.isClosed()) {
391 dbc = createNewDatabaseConnection();
392 }
393 return dbc;
394 } catch (Exception e) {
395 return null;
396 }
397 }
398
399 private Connection createNewDatabaseConnection() throws SQLException {
400 try {
401 Class.forName("org.postgresql.Driver");
402 } catch (ClassNotFoundException e) {
403 throw new RuntimeException(e);
404 }
405 String url = "jdbc:postgresql://" + getHost()
406 // + (":" + PropertyUtils.getDbPort())
407 + ("/" + getDatabase());
408
409 String password = getPassword();
410 String username = getUsername();
411
412 // log.debug("DB URL: " + url + " u=" + username + " p="
413 // + password);
414
415 return DriverManager.getConnection(url, username, password);
416 }
417
418 public String[] getDescribedTablesWithGeometry() {
419
420 if (cachedGeometryTableNames == null) {
421
422 Connection dc;
423 try {
424 dc = createNewDatabaseConnection();
425 try {
426
427 cachedGeometryTableNames = PGUtil
428 .getColumnsDescribedInGeometryColumnsTable(dc
429 .createStatement());
430
431 } catch (SQLException e) {
432 log.error(e, e);
433 } finally {
434 dc.close();
435 }
436 } catch (SQLException e1) {
437 log.error(e1, e1);
438 return new String[0];
439 }
440 }
441 return cachedGeometryTableNames;
442 }
443
444 @Override
445 protected void finalize() throws Throwable {
446 super.finalize();
447 dispose();
448 }
449
450 public void dispose() {
451 try {
452 if (dbc != null && !dbc.isClosed()) {
453 dbc.close();
454 dbc = null;
455 }
456 } catch (SQLException e) {
457 log.error("Error while disposing the database connection to "
458 + toString(), e);
459 }
460 }
461 }

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