Statistics
| Revision:

svn-gvsig-desktop / branches / v2_0_0_prep / extensions / extGeoDB / src / org / gvsig / geodb / vectorialdb / wizard / WizardDB.java @ 34114

History | View | Annotate | Download (18.1 KB)

1
/* gvSIG. Geographic Information System of the Valencian Government
2
*
3
* Copyright (C) 2007-2008 Infrastructures and Transports Department
4
* of the Valencian Government (CIT)
5
*
6
* This program is free software; you can redistribute it and/or
7
* modify it under the terms of the GNU General Public License
8
* as published by the Free Software Foundation; either version 2
9
* of the License, or (at your option) any later version.
10
*
11
* This program is distributed in the hope that it will be useful,
12
* but WITHOUT ANY WARRANTY; without even the implied warranty of
13
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
* GNU General Public License for more details.
15
*
16
* You should have received a copy of the GNU General Public License
17
* along with this program; if not, write to the Free Software
18
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
* MA  02110-1301, USA.
20
*
21
*/
22

    
23
/*
24
* AUTHORS (In addition to CIT):
25
* 2009 IVER T.I   {{Task}}
26
*/
27

    
28
package org.gvsig.geodb.vectorialdb.wizard;
29

    
30
import java.awt.BorderLayout;
31
import java.awt.Window;
32
import java.awt.event.ActionEvent;
33
import java.awt.event.ActionListener;
34
import java.util.ArrayList;
35
import java.util.Iterator;
36
import java.util.List;
37
import java.util.Map;
38
import java.util.Map.Entry;
39

    
40
import javax.swing.DefaultListModel;
41
import javax.swing.ImageIcon;
42
import javax.swing.JComboBox;
43
import javax.swing.JOptionPane;
44
import javax.swing.JPanel;
45
import javax.swing.JScrollPane;
46
import javax.swing.ListSelectionModel;
47
import javax.swing.event.ListSelectionEvent;
48
import javax.swing.event.ListSelectionListener;
49

    
50
import org.apache.commons.collections.map.HashedMap;
51
import org.gvsig.andami.PluginServices;
52
import org.gvsig.andami.PluginsLocator;
53
import org.gvsig.andami.PluginsManager;
54
import org.gvsig.andami.messages.NotificationManager;
55
import org.gvsig.app.ApplicationLocator;
56
import org.gvsig.app.ApplicationManager;
57
import org.gvsig.app.gui.WizardPanel;
58
import org.gvsig.app.prepareAction.PrepareContext;
59
import org.gvsig.app.project.Project;
60
import org.gvsig.app.project.ProjectManager;
61
import org.gvsig.app.project.documents.table.TableDocument;
62
import org.gvsig.app.project.documents.table.TableManager;
63
import org.gvsig.fmap.dal.DALLocator;
64
import org.gvsig.fmap.dal.DataManager;
65
import org.gvsig.fmap.dal.DataStoreParameters;
66
import org.gvsig.fmap.dal.exception.DataException;
67
import org.gvsig.fmap.dal.exception.InitializeException;
68
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
69
import org.gvsig.fmap.dal.feature.FeatureStore;
70
import org.gvsig.fmap.dal.serverexplorer.db.DBServerExplorer;
71
import org.gvsig.fmap.dal.serverexplorer.db.DBServerExplorerParameters;
72
import org.gvsig.fmap.dal.store.db.DBStoreParameters;
73
import org.gvsig.fmap.mapcontext.layers.FLayer;
74
import org.gvsig.fmap.mapcontrol.MapControl;
75
import org.gvsig.geodb.ExtDB_Spatial;
76
import org.gvsig.gui.beans.swing.JButton;
77
import org.gvsig.tools.dynobject.DynObject;
78
import org.slf4j.Logger;
79
import org.slf4j.LoggerFactory;
80

    
81

    
82
public class WizardDB extends WizardPanel implements ActionListener,
83
                ListSelectionListener {
84

    
85
        /**
86
     * 
87
     */
88
    private static final long serialVersionUID = -7045762275505941695L;
89
    private static final String WIZARD_TAB_NAME = "DB";
90
        private static Logger logger = LoggerFactory.getLogger(WizardDB.class
91
                        .getName());
92

    
93
    private JPanel namePanel = null;
94
        private JPanel tablesPanel = null;
95
        private JScrollPane tablesScrollPane = null;
96
        private AvailableTablesCheckBoxList tablesList = null;
97
        private JComboBox datasourceComboBox = null;
98
        private UserSelectedFieldsPanel fieldsPanel = null;
99
        private UserSelectedFieldsPanel emptyFieldsPanel = null;
100
        private JButton dbButton = null;
101
        private DBServerExplorerParameters dbExplorerParameters;
102

    
103
    private UserTableSettingsPanel settingsPanel = null;
104
        protected UserTableSettingsPanel emptySettingsPanel = null;
105
        private PrepareContext prepareDSContext;
106

    
107
    public WizardDB() {
108
                super();
109
                initialize();
110
        }
111

    
112

    
113
        protected void initialize() {
114
                setTabName(WIZARD_TAB_NAME);
115
                setLayout(null);
116
                setSize(512, 478);
117

    
118

    
119

    
120
                emptyFieldsPanel = new UserSelectedFieldsPanel(null, true, this);
121
                add(emptyFieldsPanel);
122

    
123
        add(getNamePanel(), null);
124
                loadVectorialDBDatasourcesCombo(null);
125

    
126
                add(getTablesPanel(), null);
127

    
128
        emptySettingsPanel = createSettingsPanel(null);
129
        add(emptySettingsPanel);
130

    
131
        }
132

    
133

    
134
    @SuppressWarnings("rawtypes")
135
    private void loadVectorialDBDatasourcesCombo(MyExplorer sel) {
136
        
137
        PluginsManager manager = PluginsLocator.getManager();
138
        DynObject values = manager.getPlugin(ExtDB_Spatial.class).getPluginProperties();
139
        Map connections = (Map) values.getDynValue("db_connections");
140
        if (connections != null){
141
            Iterator it = connections.entrySet().iterator();
142
            getDatasourceComboBox().removeAllItems();
143
            while (it.hasNext()){
144
                Map.Entry entry = (Entry) it.next();
145
                MyExplorer myExplorer = new MyExplorer();
146
                myExplorer.setDbExplorerParameters((DBServerExplorerParameters) entry.getValue());
147
                myExplorer.setName((String) entry.getKey());
148
                getDatasourceComboBox().addItem(myExplorer);
149
                if(sel!=null && sel.getName().equalsIgnoreCase(myExplorer.getName())){
150
                    getDatasourceComboBox().setSelectedItem(myExplorer);
151
                }
152
            }
153
        } else {
154
            connections = new HashedMap();
155
            values.setDynValue("db_connections", connections);
156
        }
157
        }
158

    
159
        public void initWizard() {
160
        }
161

    
162
        public void execute() {
163
                TablesListItem[] tables = getSelectedTables();
164

    
165
                DataManager man = DALLocator.getDataManager();
166
                FeatureStore store;
167
                
168
                String docName;
169
                TableDocument document;
170
                Project project = ProjectManager.getInstance().getCurrentProject();
171

    
172
                ApplicationManager appGvSIGMan = ApplicationLocator.getManager();
173
                PrepareContext context = this.getPrepareDataStoreContext();
174
                DBStoreParameters storeParams;
175
                for (TablesListItem table : tables) {
176
                        storeParams = getParameterForTable(table);
177

    
178
                        try {
179
                                storeParams = (DBStoreParameters) appGvSIGMan
180
                                                .prepareOpenDataStoreParameters(storeParams, context);
181
                        } catch (Exception e2) {
182
                                NotificationManager.addError(e2);
183
                                continue;
184
                        }
185

    
186
                        UserTableSettingsPanel userTableSettingsPanel = table
187
                                        .getUserTableSettingsPanel();
188

    
189
                        docName = userTableSettingsPanel.getUserLayerName();
190
                        try {
191
                                store = (FeatureStore) man.openStore(storeParams.getDataStoreName(), storeParams);
192
                        } catch (Exception e) {
193
                                NotificationManager.addError(e);
194
                                return;
195
                        }
196

    
197
                        try {
198
                                appGvSIGMan.pepareOpenDataSource(
199
                                                store, context);
200
                        } catch (Exception e) {
201
                                NotificationManager.addError(e);
202
                                store.dispose();
203
                                return;
204
                        }
205

    
206
                        document = (TableDocument) ProjectManager.getInstance().createDocument(TableManager.TYPENAME, docName);
207
                        document.setStore(store);
208
                        project.add(document);
209

    
210
                }
211

    
212
        }
213

    
214
        protected DBStoreParameters getParameterForTable(TablesListItem table) {
215
                DBStoreParameters parameters = table.getParameters();
216

    
217
                UserTableSettingsPanel userTableSettingsPanel = table
218
                                .getUserTableSettingsPanel();
219

    
220

    
221

    
222
                String fidField = userTableSettingsPanel.getIdFieldName();
223
                if (!(fidField.startsWith("{") && fidField.endsWith("}"))) {
224
                        parameters.setPkFields(new String[] { fidField });
225
                        fidField = null;
226
                }
227
                String[] fields = table.getUserSelectedFieldsPanel()
228
                                .getUserSelectedFields(fidField, null);
229

    
230
                if (userTableSettingsPanel.isSqlActive()) {
231
                        String whereClause = userTableSettingsPanel
232
                                        .getWhereClause();
233
                        parameters.setBaseFilter(whereClause);
234
                } else {
235
                        parameters.setBaseFilter("");
236
                }
237

    
238
                parameters.setFields(fields);
239

    
240

    
241
                return parameters;
242

    
243
        }
244

    
245
        @SuppressWarnings({ "rawtypes", "unchecked" })
246
    protected TablesListItem[] getSelectedTables() {
247
                int count = tablesList.getModel().getSize();
248
                ArrayList resp = new ArrayList();
249

    
250
                for (int i = 0; i < count; i++) {
251
                        TablesListItem item = (TablesListItem) tablesList.getModel()
252
                                        .getElementAt(i);
253

    
254
                        if (item.isSelected()) {
255
                                resp.add(item);
256
                        }
257
                }
258

    
259
                return (TablesListItem[]) resp.toArray(new TablesListItem[0]);
260
        }
261

    
262
        /**
263
         * This method initializes namePanel
264
         *
265
         * @return javax.swing.JPanel
266
         */
267
        private JPanel getNamePanel() {
268
                if (namePanel == null) {
269
                        namePanel = new JPanel();
270
                        namePanel.setLayout(null);
271
                        namePanel.setBounds(new java.awt.Rectangle(5, 5, 501, 51));
272
                        namePanel.setBorder(javax.swing.BorderFactory.createTitledBorder(
273
                                        null, PluginServices.getText(this, "choose_connection"),
274
                                        javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
275
                                        javax.swing.border.TitledBorder.DEFAULT_POSITION, null,
276
                                        null));
277
                        namePanel.add(getDatasourceComboBox(), null);
278
                        namePanel.add(getJdbcButton(), null);
279
                }
280

    
281
                return namePanel;
282
        }
283

    
284
        /**
285
         * This method initializes tablesPanel
286
         *
287
         * @return javax.swing.JPanel
288
         */
289
        private JPanel getTablesPanel() {
290
                if (tablesPanel == null) {
291
                        tablesPanel = new JPanel();
292
                        tablesPanel.setLayout(new BorderLayout());
293
                        tablesPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(
294
                                        null, PluginServices.getText(this, "choose_table"),
295
                                        javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
296
                                        javax.swing.border.TitledBorder.DEFAULT_POSITION, null,
297
                                        null));
298
                        tablesPanel.setBounds(new java.awt.Rectangle(5, 55, 246, 166));
299
                        tablesPanel
300
                                        .add(getTablesScrollPane(), java.awt.BorderLayout.CENTER);
301
                }
302

    
303
                return tablesPanel;
304
        }
305

    
306
        /**
307
         * This method initializes settingsPanel
308
         *
309
         * @return javax.swing.JPanel
310
         */
311

    
312
        /**
313
         * This method initializes tablesScrollPane
314
         *
315
         * @return javax.swing.JScrollPane
316
         */
317
        private JScrollPane getTablesScrollPane() {
318
                if (tablesScrollPane == null) {
319
                        tablesScrollPane = new JScrollPane();
320
                        tablesScrollPane.setViewportView(getTablesList());
321
                }
322

    
323
                return tablesScrollPane;
324
        }
325

    
326
        /**
327
         * This method initializes tablesList
328
         *
329
         * @return javax.swing.JList
330
         */
331
        protected AvailableTablesCheckBoxList getTablesList() {
332
                if (tablesList == null) {
333
                        tablesList = new AvailableTablesCheckBoxList(this);
334
                        tablesList.addListSelectionListener(this);
335
                        tablesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
336
                }
337

    
338
                return tablesList;
339
        }
340

    
341
        /**
342
         * This method initializes layerNameTextField
343
         *
344
         * @return javax.swing.JTextField
345
         */
346

    
347
        /**
348
         * This method initializes jComboBox
349
         *
350
         * @return javax.swing.JComboBox
351
         */
352
        private JComboBox getDatasourceComboBox() {
353
                if (datasourceComboBox == null) {
354
                        datasourceComboBox = new JComboBox();
355
                        datasourceComboBox
356
                                        .setBounds(new java.awt.Rectangle(10, 20, 446, 21));
357
                        datasourceComboBox.addActionListener(this);
358
                }
359

    
360
                return datasourceComboBox;
361
        }
362

    
363
        public void actionPerformed(ActionEvent arg0) {
364
                if (datasourceComboBox.getItemCount() == 0) {
365
                        setEmptyPanels();
366
                }
367
                Object src = arg0.getSource();
368

    
369
                if (src == datasourceComboBox) {
370
                 MyExplorer sel_obj = (MyExplorer)datasourceComboBox.getSelectedItem();
371

    
372
                        if (sel_obj == null) {
373
                                return;
374
                        }
375
                        getDatasourceComboBox().repaint();
376
            dbExplorerParameters = sel_obj.getDbSeverExplorerParameters();
377

    
378
                } else if (src == dbButton) {
379
                        MyExplorer sel = addNewConnection();
380

    
381
                        if (sel != null) {
382
                                dbExplorerParameters = sel.getDbSeverExplorerParameters();
383
                                loadVectorialDBDatasourcesCombo(sel);
384
                                getDatasourceComboBox().setSelectedItem(sel);
385

    
386
                        }
387
                }
388
                
389
                updateTableList(dbExplorerParameters);
390
        }
391

    
392
        @SuppressWarnings({ "unchecked", "rawtypes" })
393
    private MyExplorer addNewConnection() {
394
                MyExplorer myExplorer = new MyExplorer();
395
                DBServerExplorerParameters resp = null;
396

    
397
                VectorialDBConnectionParamsDialog newco = new VectorialDBConnectionParamsDialog();
398
                newco.showDialog();
399

    
400
                if (newco.isOkPressed()) {
401
                        try {
402
                                resp = newco.getParameters();
403
                        } catch (Exception e) {
404
                                showConnectionErrorMessage(e.getMessage());
405
                                return null;
406
                        }
407
                        PluginsManager manager = PluginsLocator.getManager();
408
            DynObject values = manager.getPlugin(ExtDB_Spatial.class).getPluginProperties();
409
            Map connections = (Map) values.getDynValue("db_connections");
410
            if(connections == null){
411
                connections = new HashedMap();
412
                values.setDynValue("db_connections", connections);
413
            }
414
            connections.put(newco.getConnectionName(), resp);
415
            
416
//                        SingleVectorialDBConnectionExtension.saveAllToPersistence();
417
                        myExplorer.setDbExplorerParameters(resp);
418
                        myExplorer.setName(newco.getConnectionName());
419
                        return myExplorer;
420
                } else {
421
                        return null;
422
                }
423
        }
424

    
425
        protected TablesListItem createTabeListItem(DBServerExplorer dbExplorer,
426
                        DBStoreParameters param) {
427
                return new TablesListItem(dbExplorer, param, this);
428
        }
429

    
430
        @SuppressWarnings("rawtypes")
431
    private void updateTableList(
432
                        DBServerExplorerParameters dbSeverExplorerParameters2) {
433
                if (dbSeverExplorerParameters2 == null) {
434
                        return;
435
                }
436
                DataManager dm = DALLocator.getDataManager();
437
                DBServerExplorer dbExplorer;
438
                try {
439
                        dbExplorer = (DBServerExplorer) dm.openServerExplorer(dbSeverExplorerParameters2.getExplorerName(), dbSeverExplorerParameters2);
440

    
441
                        // TODO: use the mode to filter tables with geometries when opening
442
                        // a view document
443
                        List parameters = dbExplorer.list();
444

    
445
                        DefaultListModel lmodel = new DefaultListModel();
446

    
447
                        Iterator iter = parameters.iterator();
448
                        DBStoreParameters param;
449
                        int count = 0;
450
                        while (iter.hasNext()) {
451
                                param = (DBStoreParameters) iter.next();
452
                                lmodel.addElement(createTabeListItem(dbExplorer, param));
453
                                count++;
454
                        }
455

    
456
                        getTablesList().setModel(lmodel);
457
                        getTablesScrollPane().setViewportView(tablesList);
458
                        tablesScrollPane.updateUI();
459
                } catch (InitializeException e) {
460
                        logger.error("While getting table names: " + e.getMessage(), e);
461
                        NotificationManager.showMessageError("While getting table names: "
462
                                        + e.getMessage(), e);
463
                        return;
464
                } catch (DataException e) {
465
                        logger.error("While getting table names: " + e.getMessage(), e);
466
                        NotificationManager.showMessageError("While getting table names: "
467
                                        + e.getMessage(), e);
468
                        return;
469
                } catch (ValidateDataParametersException e) {
470
                        logger.error("While getting table names: " + e.getMessage(), e);
471
                        NotificationManager.showMessageError("While getting table names: "
472
                                        + e.getMessage(), e);
473
                        return;
474
                }
475
        }
476

    
477
        public void valueChanged(ListSelectionEvent arg0) {
478
                Object src = arg0.getSource();
479

    
480
                if (src == tablesList) {
481
                        TablesListItem selected = (TablesListItem) tablesList
482
                                        .getSelectedValue();
483

    
484
                        setSettingsPanels(selected);
485
                        checkFinishable();
486
                }
487
        }
488

    
489
        private boolean validFormSettings() {
490
                int count = tablesList.getModel().getSize();
491

    
492
                boolean at_least_one = false;
493
                boolean resp = true;
494

    
495
                for (int i = 0; i < count; i++) {
496
                        TablesListItem item = (TablesListItem) tablesList.getModel()
497
                                        .getElementAt(i);
498

    
499
                        if (item.isSelected()) {
500
                                at_least_one = true;
501
                        }
502

    
503
                        if (item.disturbsWizardValidity()) {
504
                                resp = false;
505
                        }
506
                }
507

    
508
                return (at_least_one && resp);
509
        }
510

    
511
        public void checkFinishable() {
512
                boolean finishable = validFormSettings();
513
                callStateChanged(finishable);
514
        }
515

    
516
        /**
517
         * This method initializes jdbcButton
518
         *
519
         * @return javax.swing.JButton
520
         */
521
        private JButton getJdbcButton() {
522
                if (dbButton == null) {
523
                        dbButton = new JButton();
524
                        dbButton.addActionListener(this);
525
                        dbButton.setToolTipText(PluginServices.getText(this,
526
                                        "add_connection"));
527
                        dbButton.setBounds(new java.awt.Rectangle(465, 20, 26, 21));
528

    
529
                        // FIXME use standard icon theme
530
                        String _file = createResourceUrl("images/jdbc.png").getFile();
531
                        dbButton.setIcon(new ImageIcon(_file));
532
                }
533

    
534
                return dbButton;
535
        }
536

    
537
        private void showConnectionErrorMessage(String _msg) {
538
                String msg = (_msg.length() > 300) ? "" : (": " + _msg);
539
                String title = PluginServices.getText(this, "connection_error");
540
                JOptionPane.showMessageDialog(this, title + msg, title,
541
                                JOptionPane.ERROR_MESSAGE);
542
        }
543

    
544
        private java.net.URL createResourceUrl(String path) {
545
                return getClass().getClassLoader().getResource(path);
546
        }
547

    
548
        public void setSettingsPanels(TablesListItem actTable) {
549
                if (actTable == null) {
550
                        setEmptyPanels();
551

    
552
                        return;
553
                }
554
                fieldsPanel = actTable.getUserSelectedFieldsPanel();
555

    
556
                removeFieldPanels();
557
                add(fieldsPanel);
558
                fieldsPanel.repaint();
559
                removeSettingsPanels();
560
                add(emptySettingsPanel);
561

    
562
                settingsPanel = createSettingsPanel(actTable);
563

    
564
                removeSettingsPanels();
565
                add(settingsPanel);
566
                settingsPanel.repaint();
567

    
568

    
569
                repaint();
570
        }
571

    
572

    
573

    
574
        protected UserTableSettingsPanel createSettingsPanel(TablesListItem actTable) {
575
                if (actTable == null) {
576
                        return new UserTableSettingsPanel(null, "", true, this, null);
577
                }
578

    
579
                return actTable.getUserTableSettingsPanel();
580
        }
581

    
582
        protected void setEmptyPanels() {
583
                removeFieldPanels();
584
                add(emptyFieldsPanel);
585
                fieldsPanel = emptyFieldsPanel;
586

    
587
                repaint();
588
        }
589

    
590
        private void removeFieldPanels() {
591
                for (int i = 0; i < getComponentCount(); i++) {
592
                        if (getComponent(i) instanceof UserSelectedFieldsPanel) {
593
                                remove(i);
594
                        }
595
                }
596
        }
597

    
598
        public DataStoreParameters[] getParameters() {
599
                try {
600
                        TablesListItem[] selected = getSelectedTables();
601
                        int count = selected.length;
602
                        DBStoreParameters[] dbParameters = new DBStoreParameters[count];
603

    
604
                        for (int i = 0; i < count; i++) {
605
                                TablesListItem item = selected[i];
606

    
607

    
608
                                dbParameters[i] = getParameterForTable(item);
609
                        }
610

    
611
                        return dbParameters;// layerArrayToGroup(all_layers, groupName);
612
                } catch (Exception e) {
613
                        logger.error("While creating jdbc layer: " + e.getMessage(), e);
614
                        NotificationManager.addError("Error al cargar la capa: "
615
                                        + e.getMessage(), e);
616
                }
617

    
618
                return null;
619
        }
620

    
621
        /**
622
         * This method process the errors found in a layer
623
         *
624
         * @param lyr
625
         * @param mapControl
626
         */
627

    
628
        protected void processErrorsOfLayer(FLayer lyr, MapControl mapControl) {
629
                // List errors = lyr.getErrors();
630
                // wp.callError(null);
631
                mapControl.getMapContext().callNewErrorEvent(null);
632
        }
633

    
634
        private void removeSettingsPanels() {
635
                for (int i = 0; i < getComponentCount(); i++) {
636
                        if (getComponent(i) instanceof UserTableSettingsPanel) {
637
                                remove(i);
638
                        }
639
                }
640
        }
641

    
642
        protected PrepareContext getPrepareDataStoreContext() {
643
                if (this.prepareDSContext == null) {
644
                        this.prepareDSContext = new PrepareContext() {
645
                                public Window getOwnerWindow() {
646
                                        return null;
647
                                }
648

    
649
                        };
650
                }
651
                return this.prepareDSContext;
652
        }
653

    
654
        @Override
655
        public void close() {
656
                // Nothing to do
657
        }
658

    
659
} // @jve:decl-index=0:visual-constraint="10,10"