Statistics
| Revision:

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

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.gvsig.gui.beans.swing.JButton;
22

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

    
40
        private JPanel pnlWizard = null;
41
        private JPanel jPanel1 = null;
42
        private JButton btnBack = null;
43
        private JButton btnNext = null;
44
        private ConnectionPanel connectionPanel = null;
45
        private DBLayerDefinitionPanel dbLayerDefinition = null;
46
        private FieldSelection fieldSelection = null;
47

    
48
        private int step = 0;
49
        private final int nsteps = 5;
50
        private static final String CONNECTION = "conn";
51
        private static final String LAYER_DEFINITION = "layerdef";
52
        private static final String FIELD_SELECTION= "fieldsel";
53
        private VectorialJDBCDriver driver;
54

    
55
        private GeomFieldSelection geomFieldSelection = null;
56
        private UniqueFieldSelection uniqueFieldSelection = null;
57

    
58
    private DatabaseMetaData dbmd = null;
59
    private String catalog = null;
60
    private String selectTable = null;
61
    private String[] theTables = null;
62
    private Connection conex = null;
63

    
64
        private HashMap settings = new HashMap();
65
        /**
66
         * This is the default constructor
67
         */
68
        public WizardJDBC() {
69
                super();
70
                initialize();
71
        }
72
        /**
73
         * This method initializes this
74
         *
75
         * @return void
76
         */
77
        private  void initialize() {
78
                setTabName("JDBC");
79
                this.setLayout(new BorderLayout());
80
                this.setSize(300, 270);
81
                this.add(getPnlWizard(), java.awt.BorderLayout.CENTER);
82
                this.add(getJPanel1(), java.awt.BorderLayout.SOUTH);
83
                connectionPanel.setDrivers(getDriverNames());
84
                enableButtons();
85

    
86

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

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

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

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

    
102
            for (int i = 0; i < servers.length; i++) {
103
                ConnectionSettings cs = new ConnectionSettings();
104
                cs.setFromString(servers[i]);
105
                settings.put(cs.getName(), cs);
106
            }
107
            getConnectionPanel().setSettings(settings);
108
        } catch (NotExistInXMLEntity e) {
109
        }
110

    
111
        }
112

    
113
        private String[] getDriverNames(){
114
                Class[] classes = new Class[] { VectorialJDBCDriver.class };
115

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

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

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

    
129
                return (String[]) ret.toArray(new String[0]);
130

    
131
        }
132

    
133
        private void enableButtons(){
134
                getBtnBack().setEnabled(step > 0);
135
                getBtnNext().setEnabled(step < nsteps - 1);
136
        }
137

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

    
236
                                        }
237
                                }
238
                        });
239
                }
240
                return btnNext;
241
        }
242

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

    
246
        // settings.put(connectionPanel.getSettingsName(), cs);
247

    
248

    
249
    }
250

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

    
255
                dbmd = conex.getMetaData();
256
        String[] types = {"TABLE", "VIEW"};
257
                ResultSet rs = dbmd.getTables(catalog, null, null, types);
258
                TreeMap ret = new TreeMap();
259
                while (rs.next()){
260
                        // ret.put(rs.getString("TABLE_NAME"), rs.getString("TABLE_NAME"));
261
                        // As suggested by Jorge Agudo, to allow chargin tables from other schemas
262
                        ret.put((rs.getString("TABLE_SCHEM")!=null?(rs.getString("TABLE_SCHEM") + "."): "") + rs.getString("TABLE_NAME"), (rs.getString("TABLE_SCHEM")!=null?(rs.getString("TABLE_SCHEM") + "."): "") + rs.getString("TABLE_NAME"));                        
263
                }
264

    
265
                return (String[]) ret.keySet().toArray(new String[0]);
266
        }
267

    
268
        private String[] getTableFields() throws SQLException, DriverLoadException{
269
                Statement st = conex.createStatement();
270
        // ResultSet rs = dbmd.getTables(catalog, null, dbLayerDefinition.getTable(), null);
271
                ResultSet rs = st.executeQuery("select * from " + dbLayerDefinition.getTable() + " LIMIT 1");
272
                ResultSetMetaData rsmd = rs.getMetaData();
273

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

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

    
280
                return ret;
281
        }
282

    
283
        /**
284
         * This method initializes connectionPanel
285
         *
286
         * @return com.iver.cit.gvsig.gui.Panels.ConnectionPanel
287
         */
288
        private ConnectionPanel getConnectionPanel() {
289
                if (connectionPanel == null) {
290
                        connectionPanel = new ConnectionPanel();
291
                        connectionPanel.setName("connectionPanel");
292
                        connectionPanel.setDrivers(getDriverNames());
293
                }
294
                return connectionPanel;
295
        }
296
        /**
297
         * This method initializes dbLayerDefinition
298
         *
299
         * @return com.iver.cit.gvsig.gui.Panels.dbLayerDefinition
300
         */
301
        private DBLayerDefinitionPanel getDbLayerDefinition() {
302
                if (dbLayerDefinition == null) {
303
                        dbLayerDefinition = new DBLayerDefinitionPanel();
304
                        dbLayerDefinition.setName("dbLayerDefinition");
305
                }
306
                return dbLayerDefinition;
307
        }
308
        /**
309
         * This method initializes fieldSelection
310
         *
311
         * @return com.iver.cit.gvsig.gui.Panels.FieldSelection
312
         */
313
        private FieldSelection getFieldSelection() {
314
                if (fieldSelection == null) {
315
                        fieldSelection = new FieldSelection();
316
                        fieldSelection.setName("fieldSelection");
317
                }
318
                return fieldSelection;
319
        }
320

    
321
        public VectorialJDBCDriver getDriver() throws DriverLoadException{
322
                if (driver == null){
323
                        driver = (VectorialJDBCDriver) LayerFactory.getDM().getDriver(connectionPanel.getDriver());
324
                }
325

    
326
                return driver;
327
        }
328

    
329
        public String getConnectionString() throws DriverLoadException{
330
                String connectionString = getDriver().getConnectionStringBeginning() + "//" + connectionPanel.getHost();
331

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

    
338
                connectionString += ("/" + connectionPanel.getDBName());
339

    
340
                return connectionString;
341
        }
342

    
343
        public String getLayerName(){
344
                return dbLayerDefinition.getLayerName();
345
        }
346

    
347
        /**
348
         * @return ONLY alphanumeric fields. You need to retrieve
349
     * the geometry fields with getGeometryField();
350
         * @throws DriverLoadException
351
         */
352
        public String[] getFields() throws DriverLoadException{
353
                String[] fields = fieldSelection.getFields();
354
                String geomField = geomFieldSelection.getField();
355
                String[] onlyAlphanumericFields = new String[fields.length-1];
356
        int newIndex = 0;
357
                for (int i = 0; i < fields.length; i++) {
358
                        if (!fields[i].equals(geomField))
359
            {
360
                                onlyAlphanumericFields[newIndex] = fields[i];
361
                newIndex++;
362
            }
363
                }
364
                return onlyAlphanumericFields;
365
        }
366

    
367
        /**
368
         * @return WhereClause (doesn't check if correct)
369
         */
370
        public String getWhereClause()
371
        {
372
                return dbLayerDefinition.getWhereClause();
373
        }
374
        /**
375
         * @return
376
         */
377
        public String getUser() {
378
                return connectionPanel.getUser();
379
        }
380
        /**
381
         * @return
382
         */
383
        public String getPassword() {
384
                return connectionPanel.getPassword();
385
        }
386
        /**
387
         * @return
388
         */
389
        public String getTable() {
390
                return dbLayerDefinition.getTable();
391
        }
392

    
393
        /**
394
         * @return Field ID (Unique Value Field we want to use has key)
395
         */
396
        public String getFID() {
397
                return uniqueFieldSelection.getField();
398
        }
399

    
400
    public String getGeomField()
401
    {
402
        return geomFieldSelection.getField();
403
    }
404

    
405
        /**
406
         * This method initializes geomFieldSelection
407
         *
408
         * @return com.iver.cit.gvsig.gui.jdbcwizard.GeomFieldSelection
409
         */
410
        private GeomFieldSelection getGeomFieldSelection() {
411
                if (geomFieldSelection == null) {
412
                        geomFieldSelection = new GeomFieldSelection();
413
                        geomFieldSelection.setName("geomFieldSelection");
414
                }
415
                return geomFieldSelection;
416
        }
417
        /**
418
         * This method initializes uniqueFieldSelection
419
         *
420
         * @return com.iver.cit.gvsig.gui.jdbcwizard.UniqueFieldSelection
421
         */
422
        private UniqueFieldSelection getUniqueFieldSelection() {
423
                if (uniqueFieldSelection == null) {
424
                        uniqueFieldSelection = new UniqueFieldSelection();
425
                        uniqueFieldSelection.setName("uniqueFieldSelection");
426
                        uniqueFieldSelection.setWizard(this);
427
                }
428
                return uniqueFieldSelection;
429
        }
430
        public void initWizard() {
431
        }
432

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

    
439
        /* (non-Javadoc)
440
         * @see com.iver.cit.gvsig.gui.WizardPanel#getLayer()
441
         */
442
        public FLayer getLayer() {
443
                WizardJDBC wiz = this;
444
            //true -> Modo desconectado. Por ahora, no se usa
445
        IProjection proj = null;
446
        String dbURL;
447
        try {
448
            dbURL = wiz.getConnectionString();
449
            String user = wiz.getUser();
450
            String pwd = wiz.getPassword();
451
            String layerName = wiz.getLayerName();
452
            String[] fields = wiz.getFields();
453
            String tableName = wiz.getTable();
454
            String whereClause = wiz.getWhereClause();
455
            String fidField = wiz.getFID();
456
            String geomField = wiz.getGeomField();
457
            Connection conn = DriverManager.getConnection(dbURL, user, pwd);
458
            conn.setAutoCommit(false);
459

    
460
            VectorialJDBCDriver driver = wiz.getDriver();
461
            if (dbLayerDefinition.getWorkingArea() != null){
462
                driver.setWorkingArea(dbLayerDefinition.getWorkingArea());
463
            }
464
            String strEPSG = getMapCtrl().getViewPort()
465
                        .getProjection().getAbrev()
466
                        .substring(5);
467
            DBLayerDefinition lyrDef = new DBLayerDefinition();
468
            lyrDef.setName(layerName);
469
            lyrDef.setTableName(tableName);
470
            lyrDef.setWhereClause(whereClause);
471
            lyrDef.setFieldNames(fields);
472
            lyrDef.setFieldGeometry(geomField);
473
            lyrDef.setFieldID(fidField);
474
            if (dbLayerDefinition.getWorkingArea() != null)
475
                lyrDef.setWorkingArea(dbLayerDefinition.getWorkingArea());
476

    
477
            lyrDef.setSRID_EPSG(strEPSG);
478
            if (driver instanceof ICanReproject)
479
            {
480
                ((ICanReproject)driver).setDestProjection(strEPSG);
481
            }
482
            driver.setData(conn, lyrDef);
483
            if (driver instanceof ICanReproject)
484
            {
485
                proj = CRSFactory.getCRS("EPSG:" + ((ICanReproject)driver).getSourceProjection());
486
            }
487

    
488
                if (false){
489
                FLayer lyr = LayerFactory.createDisconnectedDBLayer(driver, layerName, proj, null);
490
                            if (lyr != null) {
491
                                    lyr.setVisible(true);
492
                            }
493

    
494
                            return lyr;
495
                }else{ // MODO CONECTADO
496
                return LayerFactory.createDBLayer(driver, layerName, proj);
497
                }
498
        } catch (Exception e) {
499
            e.printStackTrace();
500
            NotificationManager.addError("Error al cargar la capa.", e);
501
        }
502

    
503
                return null;
504
        }
505
}