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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1383 - (show annotations)
Wed Jan 26 13:46:20 2011 UTC (14 years, 1 month ago) by alfonx
File MIME type: text/plain
File size: 12237 byte(s)
trunk becomes 2.4.x ... starting to create multiple modules

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

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