Statistics
| Revision:

svn-gvsig-desktop / tags / v10_RC2c / extensions / extJDBC / src / com / iver / cit / gvsig / jdbc_spatial / gui / jdbcwizard / WizardJDBC.java @ 8745

History | View | Annotate | Download (15 KB)

1
package com.iver.cit.gvsig.jdbc_spatial.gui.jdbcwizard;
2

    
3
import java.awt.BorderLayout;
4
import java.awt.CardLayout;
5
import java.awt.FlowLayout;
6
import java.sql.Connection;
7
import java.sql.DatabaseMetaData;
8
import java.sql.DriverManager;
9
import java.sql.ResultSet;
10
import java.sql.ResultSetMetaData;
11
import java.sql.SQLException;
12
import java.sql.Statement;
13
import java.util.ArrayList;
14
import java.util.HashMap;
15
import java.util.TreeMap;
16

    
17
import javax.swing.JOptionPane;
18
import javax.swing.JPanel;
19

    
20
import org.cresques.cts.IProjection;
21
import org.cresques.cts.ProjectionPool;
22
import org.gvsig.gui.beans.swing.JButton;
23

    
24
import com.hardcode.driverManager.DriverLoadException;
25
import com.iver.andami.PluginServices;
26
import com.iver.andami.messages.NotificationManager;
27
import com.iver.cit.gvsig.fmap.core.ICanReproject;
28
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
29
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
30
import com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver;
31
import com.iver.cit.gvsig.fmap.layers.FLayer;
32
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
33
import com.iver.cit.gvsig.gui.WizardPanel;
34
import com.iver.utiles.NotExistInXMLEntity;
35
import com.iver.utiles.XMLEntity;
36
/**
37
 * @author Fernando Gonz?lez Cort?s
38
 */
39
public class WizardJDBC extends WizardPanel{
40

    
41
        private JPanel pnlWizard = null;
42
        private JPanel jPanel1 = null;
43
        private JButton btnBack = null;
44
        private JButton btnNext = null;
45
        private ConnectionPanel connectionPanel = null;
46
        private DBLayerDefinitionPanel dbLayerDefinition = null;
47
        private FieldSelection fieldSelection = null;
48
        
49
        private int step = 0;
50
        private final int nsteps = 5;
51
        private static final String CONNECTION = "conn";
52
        private static final String LAYER_DEFINITION = "layerdef";
53
        private static final String FIELD_SELECTION= "fieldsel";
54
        private VectorialJDBCDriver driver;
55
        
56
        private GeomFieldSelection geomFieldSelection = null;
57
        private UniqueFieldSelection uniqueFieldSelection = null;
58
    
59
    private DatabaseMetaData dbmd = null;
60
    private String catalog = null;
61
    private String selectTable = null;
62
    private String[] theTables = null;
63
    private Connection conex = null; 
64
        
65
        private HashMap settings = new HashMap();
66
        /**
67
         * This is the default constructor
68
         */
69
        public WizardJDBC() {
70
                super();
71
                initialize();
72
        }
73
        /**
74
         * This method initializes this
75
         * 
76
         * @return void
77
         */
78
        private  void initialize() {
79
                setTabName("JDBC");
80
                this.setLayout(new BorderLayout());
81
                this.setSize(300, 270);
82
                this.add(getPnlWizard(), java.awt.BorderLayout.CENTER);
83
                this.add(getJPanel1(), java.awt.BorderLayout.SOUTH);
84
                connectionPanel.setDrivers(getDriverNames());
85
                enableButtons();
86
                
87

    
88
        XMLEntity xml = PluginServices.getPluginServices(this)
89
                                      .getPersistentXML();
90

    
91
        if (xml == null) {
92
            xml = new XMLEntity();
93
        }
94

    
95
        if (!xml.contains("jdbc-connections")) {
96
            String[] servers = new String[0];
97
            xml.putProperty("jdbc-connections", servers);
98
        }
99

    
100
        try {
101
            String[] servers = xml.getStringArrayProperty("jdbc-connections");
102

    
103
            for (int i = 0; i < servers.length; i++) {
104
                ConnectionSettings cs = new ConnectionSettings();
105
                cs.setFromString(servers[i]);
106
                settings.put(cs.getName(), cs);
107
            }
108
            getConnectionPanel().setSettings(settings);
109
        } catch (NotExistInXMLEntity e) {
110
        }
111
                
112
        }
113
        
114
        private String[] getDriverNames(){
115
                Class[] classes = new Class[] { VectorialJDBCDriver.class };
116

    
117
                ArrayList ret = new ArrayList();
118
                String[] driverNames = LayerFactory.getDM().getDriverNames();
119

    
120
                for (int i = 0; i < driverNames.length; i++) {
121
                        boolean is = false;
122

    
123
                        for (int j = 0; j < classes.length; j++) {
124
                                if (LayerFactory.getDM().isA(driverNames[i], classes[j])) {
125
                                        ret.add(driverNames[i]);
126
                                }
127
                        }
128
                }
129

    
130
                return (String[]) ret.toArray(new String[0]);
131
                
132
        }
133
        
134
        private void enableButtons(){
135
                getBtnBack().setEnabled(step > 0);
136
                getBtnNext().setEnabled(step < nsteps - 1);
137
        }
138
        
139
        /**
140
         * This method initializes pnlWizard        
141
         *         
142
         * @return javax.swing.JPanel        
143
         */    
144
        private JPanel getPnlWizard() {
145
                if (pnlWizard == null) {
146
                        pnlWizard = new JPanel();
147
                        pnlWizard.setLayout(new CardLayout());
148
                        pnlWizard.add(getConnectionPanel(), CONNECTION);
149
                        pnlWizard.add(getDbLayerDefinition(), LAYER_DEFINITION);
150
                        pnlWizard.add(getFieldSelection(), FIELD_SELECTION);
151
                        pnlWizard.add(getGeomFieldSelection(), getGeomFieldSelection().getName());
152
                        pnlWizard.add(getUniqueFieldSelection(), getUniqueFieldSelection().getName());
153
                }
154
                return pnlWizard;
155
        }
156
        /**
157
         * This method initializes jPanel1        
158
         *         
159
         * @return javax.swing.JPanel        
160
         */    
161
        private JPanel getJPanel1() {
162
                if (jPanel1 == null) {
163
                        FlowLayout flowLayout1 = new FlowLayout(FlowLayout.RIGHT);
164
                        jPanel1 = new JPanel();
165
                        jPanel1.setLayout(flowLayout1);
166
                        jPanel1.setPreferredSize(new java.awt.Dimension(10,30));
167
                        flowLayout1.setHgap(5);
168
                        flowLayout1.setVgap(4);
169
                        jPanel1.add(getBtnBack(), null);
170
                        jPanel1.add(getBtnNext(), null);
171
                }
172
                return jPanel1;
173
        }
174
        /**
175
         * This method initializes btnBack        
176
         *         
177
         * @return javax.swing.JButton        
178
         */    
179
        private JButton getBtnBack() {
180
                if (btnBack == null) {
181
                        btnBack = new JButton();
182
                        btnBack.setText(PluginServices.getText(this, "back"));
183
                        //btnBack.setPreferredSize(new java.awt.Dimension(93,18));
184
                        btnBack.addActionListener(new java.awt.event.ActionListener() { 
185
                                public void actionPerformed(java.awt.event.ActionEvent e) {    
186
                                        step--;
187
                                        enableButtons();
188
                                        ((CardLayout)pnlWizard.getLayout()).previous(pnlWizard);
189
                                }
190
                        });
191
                }
192
                return btnBack;
193
        }
194
        /**
195
         * This method initializes btnNext        
196
         *         
197
         * @return javax.swing.JButton        
198
         */    
199
        private JButton getBtnNext() {
200
                if (btnNext == null) {
201
                        btnNext = new JButton();
202
                        btnNext.setText(PluginServices.getText(this, "next"));
203
                        //btnNext.setPreferredSize(new java.awt.Dimension(93,18));
204
                        btnNext.addActionListener(new java.awt.event.ActionListener() { 
205
                                public void actionPerformed(java.awt.event.ActionEvent e) {
206
                                        boolean done = false;
207
                                        if (step == 0) done = connectionPanel.done();
208
                                        else if (step == 1) done = dbLayerDefinition.done();
209
                                        else if (step == 2) done = fieldSelection.done();
210
                                        else if (step == 3) done = geomFieldSelection.done();
211
                                        if (done){
212
                                                try {
213
                                                        if (step == 0){
214
                                catalog = connectionPanel.getDBName();
215
                                theTables = getTableNames();
216
                                                                dbLayerDefinition.setTables(theTables);
217
                                                            saveConnection();
218
                                                        }
219
                                                        else if (step == 1) {
220
                                                                fieldSelection.setFields(getTableFields());
221
                                                        }else if (step == 2) {
222
                                                                geomFieldSelection.setFields(getTableFields());
223
                                                        }else if (step == 3) {
224
                                                                uniqueFieldSelection.setFields(getTableFields());
225
                                                        }
226
                                                        step++;
227
                                                        enableButtons();
228
                                                        ((CardLayout)pnlWizard.getLayout()).next(pnlWizard);
229
                                                } catch (SQLException e1) {
230
                                                        NotificationManager.addError(PluginServices.getText(this,"error_conexion"), e1);
231
                                                } catch (DriverLoadException e1) {
232
                                                        NotificationManager.addError("No se pudo cargar el driver", e1);
233
                                                }
234
                                        }else{
235
                                                JOptionPane.showMessageDialog(WizardJDBC.this, "No estan todos los datos rellenos", "Error", JOptionPane.ERROR_MESSAGE);
236
                                                
237
                                        }
238
                                }
239
                        });
240
                }
241
                return btnNext;
242
        }
243

    
244
    private void saveConnection() {
245
        connectionPanel.saveConnectionSettings();
246

    
247
        // settings.put(connectionPanel.getSettingsName(), cs);
248
        
249
        
250
    }
251

    
252
    private String[] getTableNames() throws SQLException, DriverLoadException {
253
                conex = DriverManager.getConnection(getConnectionString(), connectionPanel.getUser(),
254
                                connectionPanel.getPassword());
255

    
256
                dbmd = conex.getMetaData();
257
        String[] types = {"TABLE", "VIEW"};
258
                ResultSet rs = dbmd.getTables(catalog, null, null, types);
259
                TreeMap ret = new TreeMap();
260
                while (rs.next()){
261
                        ret.put(rs.getString("TABLE_NAME"), rs.getString("TABLE_NAME"));
262
                }
263
                        
264
                return (String[]) ret.keySet().toArray(new String[0]);
265
        }
266
        
267
        private String[] getTableFields() throws SQLException, DriverLoadException{
268
                Statement st = conex.createStatement();
269
        // ResultSet rs = dbmd.getTables(catalog, null, dbLayerDefinition.getTable(), null);
270
                ResultSet rs = st.executeQuery("select * from " + dbLayerDefinition.getTable() + " LIMIT 1");
271
                ResultSetMetaData rsmd = rs.getMetaData();
272

    
273
                String[] ret = new String[rsmd.getColumnCount()];
274

    
275
                for (int i = 0; i < ret.length; i++) {
276
                        ret[i] = rsmd.getColumnName(i+1);
277
                }
278

    
279
                return ret;
280
        }
281
        
282
        /**
283
         * This method initializes connectionPanel        
284
         *         
285
         * @return com.iver.cit.gvsig.gui.Panels.ConnectionPanel        
286
         */    
287
        private ConnectionPanel getConnectionPanel() {
288
                if (connectionPanel == null) {
289
                        connectionPanel = new ConnectionPanel();
290
                        connectionPanel.setName("connectionPanel");
291
                        connectionPanel.setDrivers(getDriverNames());
292
                }
293
                return connectionPanel;
294
        }
295
        /**
296
         * This method initializes dbLayerDefinition        
297
         *         
298
         * @return com.iver.cit.gvsig.gui.Panels.dbLayerDefinition        
299
         */    
300
        private DBLayerDefinitionPanel getDbLayerDefinition() {
301
                if (dbLayerDefinition == null) {
302
                        dbLayerDefinition = new DBLayerDefinitionPanel();
303
                        dbLayerDefinition.setName("dbLayerDefinition");
304
                }
305
                return dbLayerDefinition;
306
        }
307
        /**
308
         * This method initializes fieldSelection        
309
         *         
310
         * @return com.iver.cit.gvsig.gui.Panels.FieldSelection        
311
         */    
312
        private FieldSelection getFieldSelection() {
313
                if (fieldSelection == null) {
314
                        fieldSelection = new FieldSelection();
315
                        fieldSelection.setName("fieldSelection");
316
                }
317
                return fieldSelection;
318
        }
319
        
320
        public VectorialJDBCDriver getDriver() throws DriverLoadException{
321
                if (driver == null){
322
                        driver = (VectorialJDBCDriver) LayerFactory.getDM().getDriver(connectionPanel.getDriver());
323
                }
324
                
325
                return driver;
326
        }
327
        
328
        public String getConnectionString() throws DriverLoadException{
329
                String connectionString = getDriver().getConnectionStringBeginning() + "//" + connectionPanel.getHost();
330

    
331
                if (connectionPanel.getPort().trim().length() > 0) {
332
                        connectionString += (":" + connectionPanel.getPort());
333
                } else {
334
                    connectionString += (":" + driver.getDefaultPort());
335
                }
336

    
337
                connectionString += ("/" + connectionPanel.getDBName());
338
                
339
                return connectionString;
340
        }
341
        
342
        public String getLayerName(){
343
                return dbLayerDefinition.getLayerName();
344
        }
345
        
346
        /**
347
         * @return ONLY alphanumeric fields. You need to retrieve
348
     * the geometry fields with getGeometryField();
349
         * @throws DriverLoadException
350
         */
351
        public String[] getFields() throws DriverLoadException{
352
                String[] fields = fieldSelection.getFields();
353
                String geomField = geomFieldSelection.getField();
354
                String[] onlyAlphanumericFields = new String[fields.length-1];
355
        int newIndex = 0;
356
                for (int i = 0; i < fields.length; i++) {
357
                        if (!fields[i].equals(geomField))
358
            {
359
                                onlyAlphanumericFields[newIndex] = fields[i];
360
                newIndex++;
361
            }
362
                }                
363
                return onlyAlphanumericFields;
364
        }
365
        
366
        /**
367
         * @return WhereClause (doesn't check if correct)
368
         */
369
        public String getWhereClause()
370
        {
371
                return dbLayerDefinition.getWhereClause();
372
        }
373
        /**
374
         * @return
375
         */
376
        public String getUser() {
377
                return connectionPanel.getUser();
378
        }
379
        /**
380
         * @return
381
         */
382
        public String getPassword() {
383
                return connectionPanel.getPassword();
384
        }
385
        /**
386
         * @return
387
         */
388
        public String getTable() {
389
                return dbLayerDefinition.getTable();
390
        }
391
        
392
        /**
393
         * @return Field ID (Unique Value Field we want to use has key)
394
         */
395
        public String getFID() {
396
                return uniqueFieldSelection.getField();
397
        }
398
    
399
    public String getGeomField()
400
    {
401
        return geomFieldSelection.getField();
402
    }
403
        
404
        /**
405
         * This method initializes geomFieldSelection        
406
         *         
407
         * @return com.iver.cit.gvsig.gui.jdbcwizard.GeomFieldSelection        
408
         */    
409
        private GeomFieldSelection getGeomFieldSelection() {
410
                if (geomFieldSelection == null) {
411
                        geomFieldSelection = new GeomFieldSelection();
412
                        geomFieldSelection.setName("geomFieldSelection");
413
                }
414
                return geomFieldSelection;
415
        }
416
        /**
417
         * This method initializes uniqueFieldSelection        
418
         *         
419
         * @return com.iver.cit.gvsig.gui.jdbcwizard.UniqueFieldSelection        
420
         */    
421
        private UniqueFieldSelection getUniqueFieldSelection() {
422
                if (uniqueFieldSelection == null) {
423
                        uniqueFieldSelection = new UniqueFieldSelection();
424
                        uniqueFieldSelection.setName("uniqueFieldSelection");
425
                        uniqueFieldSelection.setWizard(this);
426
                }
427
                return uniqueFieldSelection;
428
        }
429
        public void initWizard() {
430
        }
431

    
432
        /* (non-Javadoc)
433
         * @see com.iver.cit.gvsig.gui.WizardPanel#execute()
434
         */
435
        public void execute() {
436
        }
437

    
438
        /* (non-Javadoc)
439
         * @see com.iver.cit.gvsig.gui.WizardPanel#getLayer()
440
         */
441
        public FLayer getLayer() {
442
                WizardJDBC wiz = this;
443
            //true -> Modo desconectado. Por ahora, no se usa
444
        IProjection proj = null;
445
        String dbURL;
446
        try {
447
            dbURL = wiz.getConnectionString();
448
            String user = wiz.getUser();
449
            String pwd = wiz.getPassword();
450
            String layerName = wiz.getLayerName();
451
            String[] fields = wiz.getFields();
452
            String tableName = wiz.getTable();
453
            String whereClause = wiz.getWhereClause();
454
            String fidField = wiz.getFID();
455
            String geomField = wiz.getGeomField();
456
            Connection conn = DriverManager.getConnection(dbURL, user, pwd);
457
            conn.setAutoCommit(false);
458
    
459
            VectorialJDBCDriver driver = wiz.getDriver();
460
            if (dbLayerDefinition.getWorkingArea() != null){
461
                driver.setWorkingArea(dbLayerDefinition.getWorkingArea());
462
            }
463
            String strEPSG = getMapCtrl().getViewPort()
464
                        .getProjection().getAbrev()
465
                        .substring(5);
466
            DBLayerDefinition lyrDef = new DBLayerDefinition();                
467
            lyrDef.setName(layerName);
468
            lyrDef.setTableName(tableName);
469
            lyrDef.setWhereClause(whereClause);
470
            lyrDef.setFieldNames(fields);
471
            lyrDef.setFieldGeometry(geomField);
472
            lyrDef.setFieldID(fidField);
473
            if (dbLayerDefinition.getWorkingArea() != null)
474
                lyrDef.setWorkingArea(dbLayerDefinition.getWorkingArea());
475
            
476
            lyrDef.setSRID_EPSG(strEPSG);
477
            if (driver instanceof ICanReproject)
478
            {                    
479
                ((ICanReproject)driver).setDestProjection(strEPSG);
480
            }
481
            driver.setData(conn, lyrDef);
482
            if (driver instanceof ICanReproject)
483
            {                                        
484
                proj = CRSFactory.getCRS("EPSG:" + ((ICanReproject)driver).getSourceProjection()); 
485
            }
486
            
487
                if (false){
488
                FLayer lyr = LayerFactory.createDisconnectedDBLayer(driver, layerName, proj, null);
489
                            if (lyr != null) {
490
                                    lyr.setVisible(true);
491
                            }
492
                
493
                            return lyr;
494
                }else{ // MODO CONECTADO                
495
                return LayerFactory.createDBLayer(driver, layerName, proj);
496
                }
497
        } catch (Exception e) {
498
            e.printStackTrace();
499
            NotificationManager.addError("Error al cargar la capa.", e);
500
        }
501
            
502
                return null;
503
        }
504
}