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

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

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1163 by alfonx, Sun Oct 24 22:55:43 2010 UTC revision 1292 by alfonx, Mon Nov 22 10:39:13 2010 UTC
# Line 2  package skrueger.geotools.io; Line 2  package skrueger.geotools.io;
2    
3  import java.awt.Component;  import java.awt.Component;
4  import java.net.MalformedURLException;  import java.net.MalformedURLException;
5    import java.sql.Connection;
6    import java.sql.DriverManager;
7    import java.sql.SQLException;
8  import java.util.HashMap;  import java.util.HashMap;
9  import java.util.regex.Pattern;  import java.util.regex.Pattern;
10    
11  import org.apache.commons.lang.ArrayUtils;  import org.apache.commons.lang.ArrayUtils;
12  import org.apache.commons.lang.StringUtils;  import org.apache.commons.lang.StringUtils;
13    import org.apache.log4j.Logger;
14  import org.geotools.data.postgis.PostgisNGDataStoreFactory;  import org.geotools.data.postgis.PostgisNGDataStoreFactory;
15  import org.geotools.jdbc.JDBCDataStore;  import org.geotools.jdbc.JDBCDataStore;
16  import org.geotools.jdbc.JDBCDataStoreFactory;  import org.geotools.jdbc.JDBCDataStoreFactory;
# Line 20  import schmitzm.swing.ManualInputOption. Line 24  import schmitzm.swing.ManualInputOption.
24  import schmitzm.swing.MultipleOptionPane;  import schmitzm.swing.MultipleOptionPane;
25  import schmitzm.swing.SelectionInputOption;  import schmitzm.swing.SelectionInputOption;
26  import schmitzm.swing.SelectionInputOption.Combo;  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   * This class describes all settings needed to connect to a WFS server. This
# Line 32  import schmitzm.swing.SelectionInputOpti Line 37  import schmitzm.swing.SelectionInputOpti
37   * connection into a {@link String} with {@link #toPropertiesString()} and   * connection into a {@link String} with {@link #toPropertiesString()} and
38   * re-import the String with {@link #parsePropertiesString(String)}.   * re-import the String with {@link #parsePropertiesString(String)}.
39   */   */
40  public class DbServerSettings extends HashMap<Object, Object> {  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");           * params.put(JDBCDataStoreFactory.DBTYPE.key, "postgis");
# Line 52  public class DbServerSettings extends Ha Line 73  public class DbServerSettings extends Ha
73          public enum Key {          public enum Key {
74          }          }
75    
76          public enum DbType {          private static Connection dbc;
                 postgis("postgresql");  
77    
78                  private final String protocolString;          /**
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                  DbType(String protocolString) {                  if (dbServer == null) {
92                          this.protocolString = protocolString;                          newCreated = true;
93                            dbServer = new DbServerSettings(DbType.postgis);
94                  }                  }
95    
96                  public String getProtocolString() {                  Combo<DbType> dpTypeInput = new SelectionInputOption.Combo<DbType>(
97                          return protocolString;                                  "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          public void setPort(java.lang.Integer port) {          /**
147                  put(JDBCDataStoreFactory.PORT.key, port);           * @return transforms the settings to a String that can be stored in a
148             *         .properties line. @see #parsePropertiesString
149             * @throws MalformedURLException
150             */
151            @Override
152            public boolean parsePropertiesString(String propString)
153                            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                            setDbType(      DbType.valueOf(split[i++]));
163    //                      DbServerSettings dbServer = new DbServerSettings(
164    //                                      DbType.valueOf(split[i++])
165    //                                      );
166    
167                            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    
176                            return true;
177                    } catch (Exception e) {
178                            Log.warn("couldn't parse " + propString, e);
179                            return false;
180                    }
181          }          }
182    
183          public java.lang.Integer getPort() {          private String[] cachedTypeNames = null;
184                  java.lang.Integer port = (java.lang.Integer) get(JDBCDataStoreFactory.PORT.key);          private String[] cachedGeometryTableNames;
185                  if (port == null)  
186                          return (java.lang.Integer) JDBCDataStoreFactory.PORT.sample;          public DbServerSettings() {
187                  return port;                  this(DbType.postgis);
188                    
189          }          }
190    
191          public void setSchema(String schema) {          public DbServerSettings(DbType dbType) {
192                  put(JDBCDataStoreFactory.SCHEMA.key, schema);                  setDbType(dbType);
193                    setHost("localhost");
194                    setSchema("public");
195                    put(JDBCDataStoreFactory.PK_METADATA_TABLE.key, null);
196          }          }
197    
198          public String getSchema() {          public DbServerSettings(String propertiesString) {
199                  return (String) get(JDBCDataStoreFactory.SCHEMA.key);                  try {
200                            parsePropertiesString(propertiesString);
201                    } catch (MalformedURLException e) {
202                            throw new RuntimeException(e);
203                    }
204          }          }
205    
206          public void setExposePrimaryKey(Boolean exportPk) {          public String[] getCachedTypeNames() {
207                  put(JDBCDataStoreFactory.EXPOSE_PK.key, exportPk);                  return cachedTypeNames;
208            }
209    
210            public String getDatabase() {
211                    return (String) get(JDBCDataStoreFactory.DATABASE.key);
212            }
213    
214            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          public Boolean getExposePrimaryKey() {          public Boolean getExposePrimaryKey() {
# Line 96  public class DbServerSettings extends Ha Line 225  public class DbServerSettings extends Ha
225                  return expk;                  return expk;
226          }          }
227    
         public void setHost(String host) {  
                 put(JDBCDataStoreFactory.HOST.key, host);  
         }  
   
228          public String getHost() {          public String getHost() {
229                  return (String) get(JDBCDataStoreFactory.HOST.key);                  return (String) get(JDBCDataStoreFactory.HOST.key);
230          }          }
231    
         public void setPassword(String password) {  
                 put(JDBCDataStoreFactory.PASSWD.key, password);  
         }  
   
232          public String getPassword() {          public String getPassword() {
233                  return (String) get(JDBCDataStoreFactory.PASSWD.key);                  return (String) get(JDBCDataStoreFactory.PASSWD.key);
234          }          }
235    
236          public void setUsername(String username) {          public java.lang.Integer getPort() {
237                  put(JDBCDataStoreFactory.USER.key, username);                  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            }
242    
243            public String getSchema() {
244                    return (String) get(JDBCDataStoreFactory.SCHEMA.key);
245          }          }
246    
247          public String getUsername() {          public String getUsername() {
248                  return (String) get(JDBCDataStoreFactory.USER.key);                  return (String) get(JDBCDataStoreFactory.USER.key);
249          }          }
250    
251          public void setDatabase(String db) {          /**
252                  put(JDBCDataStoreFactory.DATABASE.key, db);           * @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          public String getDatabase() {                  if (getHost() == null)
260                  return (String) get(JDBCDataStoreFactory.DATABASE.key);                          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          }          }
276    
277          /**          public void setCachedTypeNames(String[] cachedTypeNames) {
278           * Character used to separate the parameters when serializing settings to a                  this.cachedTypeNames = cachedTypeNames;
279           * String          }
          */  
         private static final String DELIMITER = "|";  
280    
281          public DbServerSettings(DbType dbType) {          public void setDatabase(String db) {
282                  setDbType(dbType);                  put(JDBCDataStoreFactory.DATABASE.key, db);
                 setHost("localhost");  
                 setSchema("public");  
283          }          }
284    
285          public void setDbType(DbType dbType) {          public void setDbType(DbType dbType) {
# Line 157  public class DbServerSettings extends Ha Line 299  public class DbServerSettings extends Ha
299    
300          }          }
301    
302          public DbType getDbType() {          public void setExposePrimaryKey(Boolean exportPk) {
303                  String dbt = (String) get(PostgisNGDataStoreFactory.DBTYPE.key);                  put(JDBCDataStoreFactory.EXPOSE_PK.key, exportPk);
                 if (dbt != null)  
                         return DbType.valueOf(dbt);  
                 return null;  
304          }          }
305    
306          public DbServerSettings() {          public void setHost(String host) {
307                    put(JDBCDataStoreFactory.HOST.key, host);
308          }          }
309    
310          /**          public void setPassword(String password) {
311           * @return <code>true</code>, if all parameters look OK, without actually                  put(JDBCDataStoreFactory.PASSWD.key, password);
312           *         opening any connection.          }
          */  
         public boolean isWellDefined() {  
                 if (getDbType() == null)  
                         return false;  
   
                 if (getHost() == null)  
                         return false;  
   
                 if (getUsername() == null)  
                         return false;  
   
                 if (getPassword() == null)  
                         return false;  
313    
314                  if (getPort() == null)          public void setPort(java.lang.Integer port) {
315                          return false;                  put(JDBCDataStoreFactory.PORT.key, port);
316            }
317    
318                  if (getSchema() == null)          public void setSchema(String schema) {
319                          return false;                  put(JDBCDataStoreFactory.SCHEMA.key, schema);
320            }
321    
322                  return true;          public void setUsername(String username) {
323                    put(JDBCDataStoreFactory.USER.key, username);
324          }          }
325    
326          /**          /**
# Line 204  public class DbServerSettings extends Ha Line 334  public class DbServerSettings extends Ha
334                  serialized.append(getDbType().toString());                  serialized.append(getDbType().toString());
335                  serialized.append(DELIMITER);                  serialized.append(DELIMITER);
336    
337                    serialized.append(getTitle());
338                    serialized.append(DELIMITER);
339    
340                  serialized.append(getHost());                  serialized.append(getHost());
341                  serialized.append(DELIMITER);                  serialized.append(DELIMITER);
342    
# Line 223  public class DbServerSettings extends Ha Line 356  public class DbServerSettings extends Ha
356                  serialized.append(DELIMITER);                  serialized.append(DELIMITER);
357    
358                  serialized.append(getSchema().toString());                  serialized.append(getSchema().toString());
359                  serialized.append(DELIMITER);                  // serialized.append(DELIMITER);
360    
361                  return serialized.toString();                  return serialized.toString();
362          }          }
363    
         /**  
          * @return transforms the settings to a String that can be stored in a  
          *         .properties line. @see #parsePropertiesString  
          * @throws MalformedURLException  
          */  
         public static DbServerSettings parsePropertiesString(String propString)  
                         throws MalformedURLException {  
   
                 if (propString == null || propString.isEmpty())  
                         throw new IllegalArgumentException("parameter to parse was empty");  
                 try {  
   
                         String[] split = propString.split(Pattern.quote(DELIMITER));  
   
                         DbType dbt = DbType.valueOf(split[0]);  
   
                         DbServerSettings dbServer = new DbServerSettings(dbt);  
   
                         dbServer.setHost(split[1]);  
                         dbServer.setPort(java.lang.Integer.valueOf(split[2]));  
                         dbServer.setUsername(StringUtils.stripToNull(split[3]));  
                         dbServer.setPassword(split[4].equals("null") ? null : split[4]);  
                         dbServer.setDatabase(split[5]);  
                         dbServer.setExposePrimaryKey(Boolean.valueOf(split[6]));  
                         dbServer.setSchema(split[7]);  
   
                         return dbServer;  
                 } catch (Exception e) {  
                         Log.warn("couldn't parse " + propString);  
                         return null;  
                 }  
         }  
   
364          @Override          @Override
365          public String toString() {          public String toString() {
366    
# Line 281  public class DbServerSettings extends Ha Line 381  public class DbServerSettings extends Ha
381                  return s.toString();                  return s.toString();
382          }          }
383    
         public void setCachedTypeNames(String[] cachedTypeNames) {  
                 this.cachedTypeNames = cachedTypeNames;  
         }  
   
         public String[] getCachedTypeNames() {  
                 return cachedTypeNames;  
         }  
   
         private String[] cachedTypeNames = null;  
   
         public String getTitle() {  
                 // TODO  
                 return "" + getDbType();  
         }  
   
384          /**          /**
385           * Opens a GUI that asks the use define a DB connection.           * returns a valid Connection to our postgresql Database. Name of database,
386             * username and password must be provided.
387           *           *
388           * @param dbServer           * @param database
389           *            <code>null</code> to create a new instance, or an instance to           *            name of the database
390           *            edit.           * @param username
391           * @return <code>null</code> if the user cancelled the creation of a new           *            a valid username
392           *         {@link DbServerSettings}, otherwise the edited instance.           * @param password
393             *            valid password
394             * @return database connection
395             * @throws SQLException
396             * @throws ClassNotFoundException
397           */           */
398          public static DbServerSettings createOrEdit(Component owner,          public Connection getDatabaseConnection() {
                         DbServerSettings dbServer) {  
                 boolean newCreated = false;  
399    
400                  if (dbServer == null) {                  try {
                         newCreated = true;  
                         dbServer = new DbServerSettings(DbType.postgis);  
                 }  
401    
402                  Combo<DbType> dpTypeInput = new SelectionInputOption.Combo<DbType>(                          if (dbc == null || dbc.isClosed()) {
403                                  "Database type", true, DbType.values(), ArrayUtils.indexOf(                                  dbc = createNewDatabaseConnection();
404                                                  DbType.values(), dbServer.getDbType()), DbType.values());                          }
405                            return dbc;
406                    } catch (Exception e) {
407                            return null;
408                    }
409            }
410    
411                  Text hostInput = new ManualInputOption.Text("Hostname", true,          private Connection createNewDatabaseConnection() throws SQLException {
412                                  dbServer.getHost());                  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                  Integer portInput = new ManualInputOption.Integer("Port", true,                  String password = getPassword();
422                                  dbServer.getPort());                  String username = getUsername();
423    
424                  Text databaseInput = new ManualInputOption.Text("Database", true,                  // log.debug("DB URL: " + url + " u=" + username + " p="
425                                  dbServer.getDatabase());                  // + password);
426    
427                  Text schemaInput = new ManualInputOption.Text("Schema", true,                  return DriverManager.getConnection(url, username, password);
428                                  dbServer.getSchema());          }
429    
430                  Text userInput = new ManualInputOption.Text("Username", true,          public String[] getDescribedTablesWithGeometry() {
                                 dbServer.getUsername());  
431    
432                  PasswordViewable passwdInput = new ManualInputOption.PasswordViewable(                  if (cachedGeometryTableNames == null) {
                                 "Password", true, dbServer.getPassword());  
433    
434                  BooleanInputOption exposePkInput = new BooleanInputOption(                          Connection dc;
435                                  "Expose primary keys", dbServer.getExposePrimaryKey());                          try {
436                                    dc = createNewDatabaseConnection();
437                                    try {
438    
439                  Object[] input = MultipleOptionPane.showMultipleInputDialog(owner,                                          cachedGeometryTableNames = PGUtil
440                                  "DB Connection paramters", dpTypeInput, hostInput, portInput,                                                          .getColumnsDescribedInGeometryColumnsTable(dc
441                                  databaseInput, schemaInput, userInput, passwdInput,                                                                          .createStatement());
                                 exposePkInput);  
442    
443                  if (input == null) {                                  } catch (SQLException e) {
444                          if (newCreated)                                          log.error(e, e);
445                                  return null;                                  } finally {
446                          else                                          dc.close();
447                                  return dbServer;                                  }
448                  } else {                          } catch (SQLException e1) {
449                          dbServer.setDbType((DbType) input[0]);                                  log.error(e1, e1);
450                          dbServer.setHost((String) input[1]);                                  return new String[0];
451                          dbServer.setPort((java.lang.Integer) input[2]);                          }
                         dbServer.setDatabase((String) input[3]);  
                         dbServer.setSchema((String) input[4]);  
                         dbServer.setUsername((String) input[5]);  
                         dbServer.setPassword(String.valueOf((char[]) input[6]));  
                         dbServer.setExposePrimaryKey((Boolean) input[7]);  
452                  }                  }
453                    return cachedGeometryTableNames;
454            }
455    
456                  return dbServer;          @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  }  }

Legend:
Removed from v.1163  
changed lines
  Added in v.1292

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26