Statistics
| Revision:

svn-gvsig-desktop / trunk / applications / appgvSIG / src / com / prodevelop / cit / gvsig / vectorialdb / wizard / WizardVectorialDB.java @ 37832

History | View | Annotate | Download (23.6 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2006 Prodevelop and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *   Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *   +34 963862235
28
 *   gvsig@gva.es
29
 *   www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   Prodevelop Integraci?n de Tecnolog?as SL
34
 *   Conde Salvatierra de ?lava , 34-10
35
 *   46004 Valencia
36
 *   Spain
37
 *
38
 *   +34 963 510 612
39
 *   +34 963 510 968
40
 *   gis@prodevelop.es
41
 *   http://www.prodevelop.es
42
 */
43
package com.prodevelop.cit.gvsig.vectorialdb.wizard;
44

    
45
import java.awt.BorderLayout;
46
import java.awt.Component;
47
import java.awt.event.ActionEvent;
48
import java.awt.event.ActionListener;
49
import java.awt.geom.Rectangle2D;
50
import java.sql.SQLException;
51
import java.util.ArrayList;
52

    
53
import javax.swing.DefaultListModel;
54
import javax.swing.ImageIcon;
55
import javax.swing.JComboBox;
56
import javax.swing.JOptionPane;
57
import javax.swing.JPanel;
58
import javax.swing.JScrollPane;
59
import javax.swing.ListSelectionModel;
60
import javax.swing.event.ListSelectionEvent;
61
import javax.swing.event.ListSelectionListener;
62

    
63
import org.apache.log4j.Logger;
64
import org.cresques.cts.IProjection;
65
import org.gvsig.gui.beans.swing.JButton;
66

    
67
import com.hardcode.driverManager.Driver;
68
import com.hardcode.driverManager.DriverLoadException;
69
import com.iver.andami.PluginServices;
70
import com.iver.andami.messages.NotificationManager;
71
import com.iver.cit.gvsig.SingleVectorialDBConnectionExtension;
72
import com.iver.cit.gvsig.fmap.core.ICanReproject;
73
import com.iver.cit.gvsig.fmap.drivers.DBException;
74
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
75
import com.iver.cit.gvsig.fmap.drivers.IConnection;
76
import com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver;
77
import com.iver.cit.gvsig.fmap.drivers.IVectorialJDBCDriver;
78
import com.iver.cit.gvsig.fmap.drivers.db.utils.ConnectionWithParams;
79
import com.iver.cit.gvsig.fmap.drivers.db.utils.SingleDBConnectionManager;
80
import com.iver.cit.gvsig.fmap.layers.FLayer;
81
import com.iver.cit.gvsig.fmap.layers.FLayers;
82
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
83
import com.iver.cit.gvsig.gui.WizardPanel;
84
import com.iver.utiles.swing.JPasswordDlg;
85

    
86

    
87
/**
88
 * Driver-independent GeoDB wizard. Queries the drivers to fill GUI controls.
89
 * Multi-table selection available.
90
 *
91
 * @author jldominguez
92
 *
93
 */
94
public class WizardVectorialDB extends WizardPanel implements ActionListener,
95
ListSelectionListener {
96
        private static Logger logger = Logger.getLogger(WizardVectorialDB.class.getName());
97

    
98
        // private DefaultDBDriver driver;
99
        protected IConnection conex = null;
100
        private ConnectionWithParams selectedDataSource = null;
101
        private JPanel namePanel = null;
102
        private JPanel tablesPanel = null;
103
        private JScrollPane tablesScrollPane = null;
104
        private AvailableTablesCheckBoxList tablesList = null;
105
        private JComboBox datasourceComboBox = null;
106
        private UserTableSettingsPanel settingsPanel = null;
107
        private UserSelectedFieldsPanel fieldsPanel = null;
108
        private UserTableSettingsPanel emptySettingsPanel = null;
109
        private UserSelectedFieldsPanel emptyFieldsPanel = null;
110
        private JButton dbButton = null;
111

    
112

    
113

    
114
        // this will be created when "Accept" button is clicked, before saying if
115
        // panel is finishable or not
116
        // private FLayer return_layer = null;
117
        
118
        public WizardVectorialDB() {
119
                super();
120
                initialize();
121
        }
122

    
123
        /**
124
         * This method initializes this
125
         *
126
         * @return void
127
         */
128
        private void initialize() {
129
                setTabName(PluginServices.getText(this, "GeoDB"));
130
                setLayout(null);
131
                setSize(512, 478);
132

    
133

    
134
                emptySettingsPanel = new UserTableSettingsPanel(null, null, "",
135
                                getMapCtrl(), true, this, null);
136
                emptyFieldsPanel = new UserSelectedFieldsPanel(null, null, true, this);
137

    
138
                add(getNamePanel(), null);
139
                loadVectorialDBDatasourcesCombo();
140

    
141
                add(getTablesPanel(), null);
142
        }
143

    
144
        protected void loadVectorialDBDatasourcesCombo() {
145
                getDatasourceComboBox().removeAllItems();
146

    
147
                getDatasourceComboBox().addItem(new ConnectionWithParams());
148

    
149
                ConnectionWithParams[] conn = SingleDBConnectionManager.instance()
150
                .getAllConnections();
151

    
152
                if (conn == null) {
153
                        return;
154
                }
155

    
156
                for (int i = 0; i < conn.length; i++) {
157
                        Driver _drv = SingleDBConnectionManager.getInstanceFromName(conn[i].getDrvName());
158
                        if (_drv != null && _drv instanceof IVectorialDatabaseDriver) {
159
                                getDatasourceComboBox().addItem(conn[i]);
160
                        }
161
                }
162
        }
163

    
164
        private String[] getDriverNames() {
165
                Class[] classes = new Class[] { IVectorialDatabaseDriver.class };
166

    
167
                ArrayList ret = new ArrayList();
168
                String[] driverNames = LayerFactory.getDM().getDriverNames();
169

    
170
                for (int i = 0; i < driverNames.length; i++) {
171
                        boolean is = false;
172

    
173
                        for (int j = 0; j < classes.length; j++) {
174
                                if (LayerFactory.getDM().isA(driverNames[i], classes[j])) {
175
                                        ret.add(driverNames[i]);
176
                                }
177
                        }
178
                }
179

    
180
                return (String[]) ret.toArray(new String[0]);
181
        }
182

    
183
        /**
184
         * Utility method to instantiate a IVectorialDataBaseDriver from its name.
185
         *
186
         * @param drvname driver's name
187
         * @return a IVectorialDataBaseDriver
188
         *
189
         * @throws DriverLoadException
190
         */
191
        public IVectorialDatabaseDriver getDriverFromName(String drvname)
192
        throws DriverLoadException {
193
                IVectorialDatabaseDriver resp =
194
                        (IVectorialDatabaseDriver) LayerFactory.getDM().getDriver(drvname);
195
                return resp;
196
        }
197

    
198
        public void initWizard() {
199
        }
200

    
201
        public void execute() {
202
                SingleVectorialDBConnectionExtension.saveAllToPersistence();
203
        }
204

    
205
        /**
206
         * Return FLayers if user performs multi selection.
207
         */
208
        public FLayer getLayer() {
209
                try {
210
                        IProjection proj = null;
211
                        TablesListItem[] selected = getSelectedTables();
212
                        int count = selected.length;
213
                        String groupName = selectedDataSource.getDb() + " (" +
214
                                        conex.getNameServer() + ")";
215

    
216
                        // AFLayer[] all_layers = new FLayer[count];
217
                        ArrayList unchecked_list = new ArrayList();
218
                        String strEPSG = getMapCtrl().getViewPort().getProjection()
219
                        .getAbrev();
220

    
221
                        for (int i = 0; i < count; i++) {
222
                                TablesListItem item = selected[i];
223

    
224
                                IVectorialDatabaseDriver driver = null;
225
                                driver = getDriverFromName(selectedDataSource.getDrvName());
226
                                UserTableSettingsPanel userTableSettingsPanel=item.getUserTableSettingsPanel(getMapCtrl().getViewPort().getProjection()
227
                                                .getAbrev());
228
                                Rectangle2D _wa = userTableSettingsPanel.getWorkingArea();
229

    
230
                                if (_wa != null) {
231
                                        driver.setWorkingArea(_wa);
232
                                }
233
                                String layerName = userTableSettingsPanel.getUserLayerName();
234
                                // Change: we parse tableName to extract schema (or owner in Oracle)
235
                                String[] tokens = item.getTableName().split("\\u002E", 2);
236
                                String tableName;
237
                                String schema = null;
238
                                if (tokens.length > 1)
239
                                {
240
                                        schema = tokens[0];
241
                                        tableName = tokens[1];
242
                                }
243
                                else
244
                                {
245
                                        tableName = tokens[0];
246
                                }
247

    
248
                                String fidField = userTableSettingsPanel.getIdFieldName();
249
                                String geomField = userTableSettingsPanel.getGeoFieldName();
250
                                String[] fields = item.getUserSelectedFieldsPanel()
251
                                .getUserSelectedFields(fidField, geomField);
252

    
253
                                //                        fields = driver.manageGeometryField(fields, geomField);
254

    
255
                                // driver.manageGeometryField(geomField);
256
                                DBLayerDefinition lyrDef = new DBLayerDefinition();
257
                                lyrDef.setName(layerName);
258
                                lyrDef.setSchema(schema);
259
                                lyrDef.setTableName(tableName);
260

    
261
                                if (userTableSettingsPanel.isSqlActive()) {
262
                                        String whereClause = userTableSettingsPanel.getWhereClause();
263
                                        lyrDef.setWhereClause(whereClause);
264
                                }
265
                                else {
266
                                        lyrDef.setWhereClause("");
267
                                }
268

    
269
                                lyrDef.setFieldGeometry(geomField);
270
                                lyrDef.setFieldNames(fields);
271

    
272
                                lyrDef.setFieldID(fidField);
273

    
274
                                if (_wa != null) {
275
                                        lyrDef.setWorkingArea(_wa);
276
                                }
277

    
278
                                lyrDef.setSRID_EPSG(strEPSG);
279

    
280
                                if (driver instanceof ICanReproject) {
281
                                        ((ICanReproject) driver).setDestProjection(strEPSG);
282
                                }
283
                                lyrDef.setHost(selectedDataSource.getHost());
284
                                lyrDef.setPort(Integer.parseInt(selectedDataSource.getPort()));
285
                                lyrDef.setDataBase(selectedDataSource.getDb());
286
                                lyrDef.setUser(selectedDataSource.getUser());
287
                                lyrDef.setPassword(selectedDataSource.getPw());
288

    
289
                                try {
290
                                        
291
                                        driver.setData(conex, lyrDef);
292
                                        if (driver instanceof ICanReproject) {
293
                                                proj = userTableSettingsPanel.getProjection();
294
                                        }
295
                                        unchecked_list.add(LayerFactory.createDBLayer(driver, layerName, proj));
296

    
297
                                } catch (Exception ex) {
298
                                        NotificationManager.addError(
299
                                                        PluginServices.getText(this, "panel_loading_exception") + " " + layerName, ex);
300
                                }
301

    
302
                        }
303

    
304
                        if (unchecked_list == null || unchecked_list.size() == 0) {
305
                                return null;
306
                        } else {
307
                                return layerArrayToGroup(unchecked_list, groupName);
308
                                
309
                        }
310
                        
311
                }
312
                catch (Exception e) {
313
                        logger.error("While creating jdbc layer: " + e.getMessage(), e);
314
                        NotificationManager.addError("Error al cargar la capa: " +
315
                                        e.getMessage(), e);
316
                }
317

    
318
                return null;
319
        }
320

    
321

    
322

    
323

    
324
        protected FLayer layerArrayToGroup(ArrayList all_layers, String name) {
325
                
326
                int sz = all_layers.size();
327
                
328
                if (sz == 0) {
329
                        return null;
330
                }
331
                
332
                if (sz == 1) {
333
                        return (FLayer) all_layers.get(0);
334
                }
335

    
336
        FLayers root = getMapCtrl().getMapContext().getLayers();
337

    
338
                FLayers group = new FLayers();//(mc,root);
339
        group.setMapContext(getMapCtrl().getMapContext());
340
                group.setParentLayer(root);
341
                group.setName(name);
342

    
343
                for (int i = 0; i < sz; i++) {
344
                        group.addLayer((FLayer) all_layers.get(i));
345
                }
346

    
347
                return group;
348
        }
349

    
350
        protected TablesListItem[] getSelectedTables() {
351
                int count = tablesList.getModel().getSize();
352
                ArrayList resp = new ArrayList();
353

    
354
                for (int i = 0; i < count; i++) {
355
                        TablesListItem item = (TablesListItem) tablesList.getModel()
356
                        .getElementAt(i);
357

    
358
                        if (item.isSelected()) {
359
                                resp.add(item);
360
                        }
361
                }
362

    
363
                return (TablesListItem[]) resp.toArray(new TablesListItem[0]);
364
        }
365

    
366
        /**
367
         * This method initializes namePanel
368
         *
369
         * @return javax.swing.JPanel
370
         */
371
        private JPanel getNamePanel() {
372
                if (namePanel == null) {
373
                        namePanel = new JPanel();
374
                        namePanel.setLayout(null);
375
                        namePanel.setBounds(new java.awt.Rectangle(5, 5, 501, 51));
376
                        namePanel.setBorder(javax.swing.BorderFactory.createTitledBorder(
377
                                        null, PluginServices.getText(this, "choose_connection"),
378
                                        javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
379
                                        javax.swing.border.TitledBorder.DEFAULT_POSITION, null, null));
380
                        namePanel.add(getDatasourceComboBox(), null);
381
                        namePanel.add(getJdbcButton(), null);
382
                }
383

    
384
                return namePanel;
385
        }
386

    
387
        /**
388
         * This method initializes tablesPanel
389
         *
390
         * @return javax.swing.JPanel
391
         */
392
        private JPanel getTablesPanel() {
393
                if (tablesPanel == null) {
394
                        tablesPanel = new JPanel();
395
                        tablesPanel.setLayout(new BorderLayout());
396
                        tablesPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(
397
                                        null, PluginServices.getText(this, "choose_table"),
398
                                        javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
399
                                        javax.swing.border.TitledBorder.DEFAULT_POSITION, null, null));
400
                        tablesPanel.setBounds(new java.awt.Rectangle(5, 55, 246, 191));
401
                        tablesPanel.add(getTablesScrollPane(), java.awt.BorderLayout.CENTER);
402
                }
403

    
404
                return tablesPanel;
405
        }
406

    
407
        /**
408
         * This method initializes settingsPanel
409
         *
410
         * @return javax.swing.JPanel
411
         */
412

    
413
        /**
414
         * This method initializes tablesScrollPane
415
         *
416
         * @return javax.swing.JScrollPane
417
         */
418
        private JScrollPane getTablesScrollPane() {
419
                if (tablesScrollPane == null) {
420
                        tablesScrollPane = new JScrollPane();
421
                        tablesScrollPane.setViewportView(getTablesList());
422
                }
423

    
424
                return tablesScrollPane;
425
        }
426

    
427
        /**
428
         * This method initializes tablesList
429
         *
430
         * @return javax.swing.JList
431
         */
432
        private AvailableTablesCheckBoxList getTablesList() {
433
                if (tablesList == null) {
434
                        tablesList = new AvailableTablesCheckBoxList(this);
435
                        tablesList.addListSelectionListener(this);
436
                        tablesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
437
                }
438

    
439
                return tablesList;
440
        }
441

    
442
        /**
443
         * This method initializes layerNameTextField
444
         *
445
         * @return javax.swing.JTextField
446
         */
447

    
448
        /**
449
         * This method initializes jComboBox
450
         *
451
         * @return javax.swing.JComboBox
452
         */
453
        protected JComboBox getDatasourceComboBox() {
454
                if (datasourceComboBox == null) {
455
                        datasourceComboBox = new JComboBox();
456
                        datasourceComboBox.setBounds(new java.awt.Rectangle(10, 20, 446, 21));
457
                        datasourceComboBox.addActionListener(this);
458
                }
459

    
460
                return datasourceComboBox;
461
        }
462

    
463
        public void actionPerformed(ActionEvent arg0) {
464
                Object src = arg0.getSource();
465

    
466
                if (src == datasourceComboBox) {
467
                        Object sel_obj = datasourceComboBox.getSelectedItem();
468

    
469
                        if (sel_obj == null) {
470
                                return;
471
                        }
472

    
473
                        if (!(sel_obj instanceof ConnectionWithParams)) {
474
                                return;
475
                        }
476

    
477
                        selectedDataSource = (ConnectionWithParams) sel_obj;
478

    
479
                        if (selectedDataSource.isNull()) {
480
                                updateTableList(selectedDataSource);
481
                                setEmptyPanels();
482

    
483
                                return;
484
                        }
485

    
486
                        if (!selectedDataSource.isConnected()) {
487
                                if (!tryToConnect(selectedDataSource)) {
488
                                        datasourceComboBox.setSelectedIndex(0);
489

    
490
                                        return;
491
                                }
492
                        }
493

    
494
                        getDatasourceComboBox().repaint();
495
                        updateTableList(selectedDataSource);
496

    
497
                        // setEmptyPanels();
498
                        return;
499
                }
500

    
501
                if (src == dbButton) {
502
                        ConnectionWithParams sel = addNewConnection();
503

    
504
                        if (sel != null) {
505
                                loadVectorialDBDatasourcesCombo();
506
                                getDatasourceComboBox().setSelectedItem(sel);
507
                        }
508
                }
509
        }
510

    
511
        private boolean tryToConnect(ConnectionWithParams _cwp) {
512
                JPasswordDlg dlg = new JPasswordDlg();
513
                dlg.setLocationRelativeTo((Component)PluginServices.getMainFrame());
514
                String strMessage = PluginServices.getText(this, "conectar_jdbc");
515
                String strPassword = PluginServices.getText(this, "password");
516
                dlg.setMessage(strMessage + " [" + _cwp.getDrvName() + ", " +
517
                                _cwp.getHost() + ", " + _cwp.getPort() + ", " + _cwp.getDb() +
518
                                ", " + _cwp.getUser() + "]. " + strPassword + "?");
519

    
520
                dlg.setVisible(true);
521

    
522
                String clave = dlg.getPassword();
523

    
524
                if (clave == null) {
525
                        return false;
526
                }
527

    
528
                try {
529
                        _cwp.connect(clave);
530
                }
531
                catch (DBException e) {
532
                        showConnectionErrorMessage(e.getMessage());
533

    
534
                        return false;
535
                }
536

    
537
                return true;
538
        }
539

    
540
        private void updateTableList(ConnectionWithParams src) {
541
                if (src.isNull()) {
542
                        getTablesList().setModel(new DefaultListModel());
543
                        getTablesScrollPane().setViewportView(tablesList);
544
                        tablesScrollPane.updateUI();
545

    
546
                        return;
547
                }
548

    
549
                conex = src.getConnection();
550

    
551
                String drvName = src.getDrvName();
552
                String dbName = "";
553

    
554
                IVectorialDatabaseDriver drv = null;
555

    
556
                try {
557
                        dbName = src.getConnection().getCatalogName();
558
                        drv = (IVectorialDatabaseDriver) LayerFactory.getDM().getDriver(drvName);
559
                }
560
                catch (Exception e) {
561
                        logger.error("While getting driver instance: " + e.getMessage(), e);
562
                }
563

    
564
                if (!(drv instanceof IVectorialDatabaseDriver)) {
565
                        logger.error(
566
                                        "Unexpected driver type (not a DefaultDBDriver driver)");
567

    
568
                        return;
569
                }
570

    
571
                String[] _tablnames = null;
572

    
573
                try {
574
                        _tablnames = drv.getTableNames(conex, dbName);
575
                        _tablnames = filterWithSchema(_tablnames, src.getSchema());
576
                } catch (DBException e) {
577
                        logger.error("While getting table names: " + e.getMessage(), e);
578

    
579
                        return;
580
                }
581

    
582
                DefaultListModel lmodel = new DefaultListModel();
583

    
584
                for (int i = 0; i < _tablnames.length; i++) {
585
                        try {
586
                                if (drv.canRead(conex, _tablnames[i])) {
587
                                        lmodel.addElement(new TablesListItem(_tablnames[i], drv, conex,
588
                                                        getMapCtrl(), this));
589
                                }
590
                        } catch (SQLException e) {
591
                                // if getTableNames works fine this exception should never be caught
592
                                logger.error("While getting table names: " + e.getMessage(), e);
593
                        }
594
                }
595

    
596
                getTablesList().setModel(lmodel);
597
                getTablesScrollPane().setViewportView(tablesList);
598
                tablesScrollPane.updateUI();
599
        }
600

    
601
        private String[] filterWithSchema(String[] tt, String sc) {
602
                
603
                if (sc==null || sc.length()==0) {
604
                        return tt;
605
                }
606
                
607
                int len = tt.length;
608
                ArrayList resp = new ArrayList();
609
                String str = "";
610
                for (int i=0; i<len; i++) {
611
                        str = tt[i];
612
                        if (str.indexOf(sc + ".") == 0) {
613
                                resp.add(str);
614
                        }
615
                }
616

    
617
                return (String[]) resp.toArray(new String[0]);
618
        }
619

    
620
        public void valueChanged(ListSelectionEvent arg0) {
621
        }
622

    
623
        private boolean validFormSettings() {
624
                int count = tablesList.getModel().getSize();
625

    
626
                boolean at_least_one = false;
627
                boolean resp = true;
628

    
629
                for (int i = 0; i < count; i++) {
630
                        TablesListItem item = (TablesListItem) tablesList.getModel()
631
                        .getElementAt(i);
632

    
633
                        if (item.isSelected()) {
634
                                at_least_one = true;
635
                        }
636

    
637
                        if (item.disturbsWizardValidity()) {
638
                                resp = false;
639
                        }
640
                }
641

    
642
                return (at_least_one && resp);
643
        }
644

    
645
        public void checkFinishable() {
646
                boolean finishable = validFormSettings();
647
                callStateChanged(finishable);
648
        }
649

    
650
        /**
651
         * This method initializes jdbcButton
652
         *
653
         * @return javax.swing.JButton
654
         */
655
         private JButton getJdbcButton() {
656
                if (dbButton == null) {
657
                        dbButton = new JButton();
658
                        dbButton.addActionListener(this);
659
                        dbButton.setToolTipText(PluginServices.getText(this,
660
                                        "add_connection"));
661
                        dbButton.setBounds(new java.awt.Rectangle(465, 20, 26, 21));
662

    
663
                        String _file = createResourceUrl("images/jdbc.png").getFile();
664
                        dbButton.setIcon(new ImageIcon(_file));
665
                }
666

    
667
                return dbButton;
668
         }
669

    
670
         private ConnectionWithParams addNewConnection() {
671
                 ConnectionWithParams resp = null;
672

    
673
                 DBConnectionParamsDialog newco = new DBConnectionParamsDialog();
674
                 newco.showDialog();
675

    
676
                 if (newco.isOkPressed()) {
677
                         String _drvname = newco.getConnectionDriverName();
678
                         String _host = newco.getConnectionServerUrl();
679
                         String _port = newco.getConnectionPort();
680
                         String _dbname = newco.getConnectionDBName();
681
                         String _user = newco.getConnectionUser();
682
                         String _pw = newco.getConnectionPassword();
683
                         String _conn_usr_name = newco.getConnectionName();
684
                         String _sche = newco.getConnectionSchema();
685

    
686
                         boolean hasToBeCon = newco.hasToBeConnected();
687

    
688
                         try {
689
                                 resp = SingleDBConnectionManager.instance()
690
                                 .getConnection(_drvname,
691
                                                 _user, _pw, _conn_usr_name, _host, _port, _dbname, _sche,
692
                                                 hasToBeCon);
693
                         }
694
                         catch (DBException e) {
695
                                 showConnectionErrorMessage(e.getMessage());
696

    
697
                                 return null;
698
                         }
699
                         SingleVectorialDBConnectionExtension.saveAllToPersistence();
700
                         return resp;
701
                 }
702
                 else {
703
                         return null;
704
                 }
705
         }
706

    
707
         private void showConnectionErrorMessage(String _msg) {
708
                 String msg = (_msg.length() > 300) ? "" : (": " + _msg);
709
                 String title = PluginServices.getText(this, "connection_error");
710
                 JOptionPane.showMessageDialog(this, title + msg, title,
711
                                 JOptionPane.ERROR_MESSAGE);
712
         }
713

    
714
         private java.net.URL createResourceUrl(String path) {
715
                 return getClass().getClassLoader().getResource(path);
716
         }
717

    
718
         public void setSettingsPanels(TablesListItem actTable)
719
         throws DBException {
720
                 if (actTable == null) {
721
                         setEmptyPanels();
722

    
723
                         return;
724
                 }
725

    
726
                 settingsPanel = actTable.getUserTableSettingsPanel(getMapCtrl().getViewPort().getProjection()
727
                                 .getAbrev());
728
                 fieldsPanel = actTable.getUserSelectedFieldsPanel();
729

    
730
                 removeFieldPanels();
731
                 add(fieldsPanel);
732
                 fieldsPanel.repaint();
733

    
734
                 removeSettingsPanels();
735
                 add(settingsPanel);
736
                 settingsPanel.repaint();
737

    
738
                 repaint();
739
         }
740

    
741
         private void setEmptyPanels() {
742
                 removeFieldPanels();
743
                 add(emptyFieldsPanel);
744
                 removeSettingsPanels();
745
                 add(emptySettingsPanel);
746

    
747
                 settingsPanel = emptySettingsPanel;
748
                 fieldsPanel = emptyFieldsPanel;
749

    
750
                 repaint();
751
         }
752

    
753
         private void removeFieldPanels() {
754
                 for (int i = 0; i < getComponentCount(); i++) {
755
                         if (getComponent(i) instanceof UserSelectedFieldsPanel) {
756
                                 remove(i);
757
                         }
758
                 }
759
         }
760

    
761
         private void removeSettingsPanels() {
762
                 for (int i = 0; i < getComponentCount(); i++) {
763
                         if (getComponent(i) instanceof UserTableSettingsPanel) {
764
                                 remove(i);
765
                         }
766
                 }
767
         }
768
         
769
         
770
         /**
771
          * @return Message describing why layers don't have good settings or
772
          * null if layers are ok.
773
          */          
774
         public String[] validateLayerSettings() {
775

    
776
                ArrayList listresp = new ArrayList();
777

    
778
                TablesListItem[] selected = getSelectedTables();
779
                int count = selected.length;
780
                ArrayList unchecked_list = new ArrayList();
781

    
782
                String strEPSG = getMapCtrl().getViewPort().getProjection().getAbrev();
783

    
784
                String layerName = "[Unknown]";
785
                for (int i = 0; i < count; i++) {
786
                        TablesListItem item = selected[i];
787

    
788
                        IVectorialDatabaseDriver _driver = null;
789
                        IVectorialJDBCDriver driver = null;
790
                        UserTableSettingsPanel utsp = null;
791

    
792
                        try {
793
                                utsp = item.getUserTableSettingsPanel(getMapCtrl()
794
                                                .getViewPort().getProjection().getAbrev());
795
                                layerName = utsp.getUserLayerName();
796
                                _driver = getDriverFromName(selectedDataSource.getDrvName());
797
                        } catch (Exception ex) {
798
                                addErrorToList(listresp, layerName, "Error_while_creating_driver");
799
                                continue; // go to next
800
                        }
801
                        
802
                        if (_driver instanceof IVectorialJDBCDriver) {
803
                                driver = (IVectorialJDBCDriver) _driver; 
804
                        } else {
805
                                logger.warn("Did not validate settings for driver: " + _driver.getClass().getName());
806
                                continue;
807
                        }
808

    
809
                        Rectangle2D _wa = utsp.getWorkingArea();
810

    
811
                        if (_wa != null) {
812
                                if ((_wa.getWidth() <= 0) || (_wa.getHeight() <= 0)) {
813
                                        addErrorToList(listresp, layerName, "Invalid_working_area");
814
                                        continue; // go to next
815
                                } else {
816
                                        driver.setWorkingArea(_wa);
817
                                }
818

    
819
                        }
820
                        // Change: we parse tableName to extract schema (or owner in Oracle)
821
                        String[] tokens = item.getTableName().split("\\u002E", 2);
822
                        String tableName;
823
                        String schema = null;
824
                        if (tokens.length > 1) {
825
                                schema = tokens[0];
826
                                tableName = tokens[1];
827
                        } else {
828
                                tableName = tokens[0];
829
                        }
830

    
831
                        String fidField = utsp.getIdFieldName();
832
                        String geomField = utsp.getGeoFieldName();
833

    
834
                        String[] fields = null;
835

    
836
                        try {
837
                                fields = item.getUserSelectedFieldsPanel()
838
                                                .getUserSelectedFields(fidField, geomField);
839
                        } catch (Exception ex) {
840
                                addErrorToList(listresp, layerName, ex.getMessage());
841
                                continue; // go to next
842
                        }
843

    
844
                        // fields = driver.manageGeometryField(fields, geomField);
845

    
846
                        // driver.manageGeometryField(geomField);
847
                        DBLayerDefinition lyrDef = new DBLayerDefinition();
848
                        lyrDef.setName(layerName);
849
                        lyrDef.setSchema(schema);
850
                        lyrDef.setTableName(tableName);
851

    
852
                        if (utsp.isSqlActive()) {
853
                                String whereClause = utsp.getWhereClause();
854
                                lyrDef.setWhereClause(whereClause);
855
                        } else {
856
                                lyrDef.setWhereClause("");
857
                        }
858

    
859
                        lyrDef.setFieldGeometry(geomField);
860
                        lyrDef.setFieldNames(fields);
861

    
862
                        lyrDef.setFieldID(fidField);
863

    
864
                        if (_wa != null) {
865
                                lyrDef.setWorkingArea(_wa);
866
                        }
867

    
868
                        lyrDef.setSRID_EPSG(strEPSG);
869

    
870
                        if (driver instanceof ICanReproject) {
871
                                ((ICanReproject) driver).setDestProjection(strEPSG);
872
                        }
873
                        lyrDef.setHost(selectedDataSource.getHost());
874
                        lyrDef.setPort(Integer.parseInt(selectedDataSource.getPort()));
875
                        lyrDef.setDataBase(selectedDataSource.getDb());
876
                        lyrDef.setUser(selectedDataSource.getUser());
877
                        lyrDef.setPassword(selectedDataSource.getPw());
878

    
879
                        try {
880
                                driver.validateData(conex, lyrDef);
881
                        } catch (Exception ex) {
882
                                addErrorToList(listresp, layerName, ex.getMessage());
883
                                continue; // go to next
884
                        }
885

    
886
                        try {
887
                                driver.close();
888
                                driver = null;
889
                        } catch (Exception ex) {
890
                        }
891

    
892
                }
893

    
894
                if (listresp.size() == 0) {
895
                        return null;
896
                } else {
897
                        String[] msgs = (String[]) listresp.toArray(new String[0]);
898
                        return msgs;
899
                }
900
        }
901

    
902
                
903
         
904
         private void addErrorToList(ArrayList lis, String lyr, String msg) {
905
                 String addstr =
906
                                PluginServices.getText(this, "Capa") + ": " + lyr + "\n" + msg;
907
                lis.add(addstr);
908
         }
909
                
910
                
911
                
912
                
913
                
914
} //  @jve:decl-index=0:visual-constraint="10,10"
915

    
916
// [eiel-gestion-conexiones]