Statistics
| Revision:

root / tags / v2_0_0_Build_2038 / extensions / extGeoDB / src / org / gvsig / geodb / vectorialdb / wizard / WizardDB.java @ 36945

History | View | Annotate | Download (18.7 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.cresques.cts.IProjection;
52
import org.slf4j.Logger;
53
import org.slf4j.LoggerFactory;
54

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

    
83

    
84
public class WizardDB extends WizardPanel implements ActionListener,
85
                ListSelectionListener {
86

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

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

    
105
    private UserTableSettingsPanel settingsPanel = null;
106
        protected UserTableSettingsPanel emptySettingsPanel = null;
107
        private PrepareContext prepareDSContext;
108

    
109
    public WizardDB() {
110
                super();
111
                initialize();
112
        }
113

    
114

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

    
120

    
121

    
122
                emptyFieldsPanel = new UserSelectedFieldsPanel(null, true, this);
123
                add(emptyFieldsPanel);
124

    
125
        add(getNamePanel(), null);
126
                loadVectorialDBDatasourcesCombo(null);
127

    
128
                add(getTablesPanel(), null);
129

    
130
        emptySettingsPanel = createSettingsPanel(null);
131
        add(emptySettingsPanel);
132

    
133
        }
134

    
135

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

    
162
        public void initWizard() {
163
        }
164

    
165
    @Override
166
    public void execute() {
167
        executeWizard();
168
    }
169

    
170
    @Override
171
    public Object executeWizard() {
172
                TablesListItem[] tables = getSelectedTables();
173

    
174
                DataManager man = DALLocator.getDataManager();
175
                FeatureStore store;
176
                
177
                String docName;
178
                TableDocument document;
179
                Project project = ProjectManager.getInstance().getCurrentProject();
180

    
181
                ApplicationManager appGvSIGMan = ApplicationLocator.getManager();
182
                PrepareContext context = this.getPrepareDataStoreContext();
183
                DBStoreParameters storeParams;
184
        List<TableDocument> tabledocs =
185
            new ArrayList<TableDocument>(tables.length);
186
                for (TablesListItem table : tables) {
187
                        storeParams = getParameterForTable(table);
188

    
189
                        try {
190
                                storeParams = (DBStoreParameters) appGvSIGMan
191
                                                .prepareOpenDataStoreParameters(storeParams, context);
192
                        } catch (Exception e2) {
193
                                NotificationManager.addError(e2);
194
                                continue;
195
                        }
196

    
197
                        UserTableSettingsPanel userTableSettingsPanel = table
198
                                        .getUserTableSettingsPanel();
199

    
200
                        docName = userTableSettingsPanel.getUserLayerName();
201
                        try {
202
                                store = (FeatureStore) man.openStore(storeParams.getDataStoreName(), storeParams);
203
                        } catch (Exception e) {
204
                                NotificationManager.addError(e);
205
                return null;
206
                        }
207

    
208
                        try {
209
                                appGvSIGMan.pepareOpenDataSource(
210
                                                store, context);
211
                        } catch (Exception e) {
212
                                NotificationManager.addError(e);
213
                                store.dispose();
214
                return null;
215
                        }
216

    
217
                        document = (TableDocument) ProjectManager.getInstance().createDocument(TableManager.TYPENAME, docName);
218
                        document.setStore(store);
219
            // project.add(document);
220
            tabledocs.add(document);
221
                }
222
        return tabledocs;
223
        }
224

    
225
        protected DBStoreParameters getParameterForTable(TablesListItem table) {
226
                DBStoreParameters parameters = table.getParameters();
227

    
228
                UserTableSettingsPanel userTableSettingsPanel = table
229
                                .getUserTableSettingsPanel();
230

    
231

    
232

    
233
                String fidField = userTableSettingsPanel.getIdFieldName();
234
                if (!(fidField.startsWith("{") && fidField.endsWith("}"))) {
235
                        parameters.setPkFields(new String[] { fidField });
236
                        fidField = null;
237
                }
238
                String[] fields = table.getUserSelectedFieldsPanel()
239
                                .getUserSelectedFields(fidField, null);
240

    
241
                if (userTableSettingsPanel.isSqlActive()) {
242
                        String whereClause = userTableSettingsPanel
243
                                        .getWhereClause();
244
                        parameters.setBaseFilter(whereClause);
245
                } else {
246
                        parameters.setBaseFilter("");
247
                }
248

    
249
                parameters.setFields(fields);
250

    
251

    
252
                return parameters;
253

    
254
        }
255

    
256
        @SuppressWarnings({ "rawtypes", "unchecked" })
257
    protected TablesListItem[] getSelectedTables() {
258
                int count = tablesList.getModel().getSize();
259
                ArrayList resp = new ArrayList();
260

    
261
                for (int i = 0; i < count; i++) {
262
                        TablesListItem item = (TablesListItem) tablesList.getModel()
263
                                        .getElementAt(i);
264

    
265
                        if (item.isSelected()) {
266
                                resp.add(item);
267
                        }
268
                }
269

    
270
                return (TablesListItem[]) resp.toArray(new TablesListItem[0]);
271
        }
272

    
273
        /**
274
         * This method initializes namePanel
275
         *
276
         * @return javax.swing.JPanel
277
         */
278
        private JPanel getNamePanel() {
279
                if (namePanel == null) {
280
                        namePanel = new JPanel();
281
                        namePanel.setLayout(null);
282
                        namePanel.setBounds(new java.awt.Rectangle(5, 5, 501, 51));
283
                        namePanel.setBorder(javax.swing.BorderFactory.createTitledBorder(
284
                                        null, PluginServices.getText(this, "choose_connection"),
285
                                        javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
286
                                        javax.swing.border.TitledBorder.DEFAULT_POSITION, null,
287
                                        null));
288
                        namePanel.add(getDatasourceComboBox(), null);
289
                        namePanel.add(getJdbcButton(), null);
290
                }
291

    
292
                return namePanel;
293
        }
294

    
295
        /**
296
         * This method initializes tablesPanel
297
         *
298
         * @return javax.swing.JPanel
299
         */
300
        private JPanel getTablesPanel() {
301
                if (tablesPanel == null) {
302
                        tablesPanel = new JPanel();
303
                        tablesPanel.setLayout(new BorderLayout());
304
                        tablesPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(
305
                                        null, PluginServices.getText(this, "choose_table"),
306
                                        javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
307
                                        javax.swing.border.TitledBorder.DEFAULT_POSITION, null,
308
                                        null));
309
                        tablesPanel.setBounds(new java.awt.Rectangle(5, 55, 246, 166));
310
                        tablesPanel
311
                                        .add(getTablesScrollPane(), java.awt.BorderLayout.CENTER);
312
                }
313

    
314
                return tablesPanel;
315
        }
316

    
317
        /**
318
         * This method initializes settingsPanel
319
         *
320
         * @return javax.swing.JPanel
321
         */
322

    
323
        /**
324
         * This method initializes tablesScrollPane
325
         *
326
         * @return javax.swing.JScrollPane
327
         */
328
        private JScrollPane getTablesScrollPane() {
329
                if (tablesScrollPane == null) {
330
                        tablesScrollPane = new JScrollPane();
331
                        tablesScrollPane.setViewportView(getTablesList());
332
                }
333

    
334
                return tablesScrollPane;
335
        }
336

    
337
        /**
338
         * This method initializes tablesList
339
         *
340
         * @return javax.swing.JList
341
         */
342
        protected AvailableTablesCheckBoxList getTablesList() {
343
                if (tablesList == null) {
344
                        tablesList = new AvailableTablesCheckBoxList(this);
345
                        tablesList.addListSelectionListener(this);
346
                        tablesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
347
                }
348

    
349
                return tablesList;
350
        }
351

    
352
        /**
353
         * This method initializes layerNameTextField
354
         *
355
         * @return javax.swing.JTextField
356
         */
357

    
358
        /**
359
         * This method initializes jComboBox
360
         *
361
         * @return javax.swing.JComboBox
362
         */
363
        private JComboBox getDatasourceComboBox() {
364
                if (datasourceComboBox == null) {
365
                        datasourceComboBox = new JComboBox();
366
                        datasourceComboBox
367
                                        .setBounds(new java.awt.Rectangle(10, 20, 446, 21));
368
                        datasourceComboBox.addActionListener(this);
369
                }
370

    
371
                return datasourceComboBox;
372
        }
373

    
374
        public void actionPerformed(ActionEvent arg0) {
375
                if (datasourceComboBox.getItemCount() == 0) {
376
                        setEmptyPanels();
377
                }
378
                Object src = arg0.getSource();
379

    
380
                if (src == datasourceComboBox) {
381
            Object selected = datasourceComboBox.getSelectedItem();
382
            if (selected instanceof MyExplorer) {
383
                MyExplorer sel_obj = (MyExplorer) selected;
384

    
385
                if (sel_obj == null) {
386
                    return;
387
                }
388
                getDatasourceComboBox().repaint();
389
                dbExplorerParameters = sel_obj.getDbSeverExplorerParameters();
390
            }
391

    
392
                } else if (src == dbButton) {
393
                        MyExplorer sel = addNewConnection();
394

    
395
                        if (sel != null) {
396
                                dbExplorerParameters = sel.getDbSeverExplorerParameters();
397
                                loadVectorialDBDatasourcesCombo(sel);
398
                                getDatasourceComboBox().setSelectedItem(sel);
399

    
400
                        }
401
                }
402
                
403
                updateTableList(dbExplorerParameters);
404
        }
405

    
406
        @SuppressWarnings({ "unchecked", "rawtypes" })
407
    private MyExplorer addNewConnection() {
408
                MyExplorer myExplorer = new MyExplorer();
409
                DBServerExplorerParameters resp = null;
410

    
411
                VectorialDBConnectionParamsDialog newco = new VectorialDBConnectionParamsDialog();
412
                newco.showDialog();
413

    
414
                if (newco.isOkPressed()) {
415
                        try {
416
                                resp = newco.getParameters();
417
                        } catch (Exception e) {
418
                                showConnectionErrorMessage(e.getMessage());
419
                                return null;
420
                        }
421
                        PluginsManager manager = PluginsLocator.getManager();
422
            DynObject values = manager.getPlugin(ExtDB_Spatial.class).getPluginProperties();
423
            Map connections = (Map) values.getDynValue("db_connections");
424
            if(connections == null){
425
                connections = new HashedMap();
426
                values.setDynValue("db_connections", connections);
427
            }
428
            connections.put(newco.getConnectionName(), resp);
429
            
430
//                        SingleVectorialDBConnectionExtension.saveAllToPersistence();
431
                        myExplorer.setDbExplorerParameters(resp);
432
                        myExplorer.setName(newco.getConnectionName());
433
                        return myExplorer;
434
                } else {
435
                        return null;
436
                }
437
        }
438

    
439
        protected TablesListItem createTabeListItem(DBServerExplorer dbExplorer,
440
                        DBStoreParameters param) {
441
                return new TablesListItem(dbExplorer, param, this);
442
        }
443

    
444
        @SuppressWarnings("rawtypes")
445
    private void updateTableList(
446
                        DBServerExplorerParameters dbSeverExplorerParameters2) {
447
                if (dbSeverExplorerParameters2 == null) {
448
                        return;
449
                }
450
                DataManager dm = DALLocator.getDataManager();
451
                DBServerExplorer dbExplorer;
452
                try {
453
                        dbExplorer = (DBServerExplorer) dm.openServerExplorer(dbSeverExplorerParameters2.getExplorerName(), dbSeverExplorerParameters2);
454

    
455
                        // TODO: use the mode to filter tables with geometries when opening
456
                        // a view document
457
                        List parameters = dbExplorer.list();
458

    
459
                        DefaultListModel lmodel = new DefaultListModel();
460

    
461
                        Iterator iter = parameters.iterator();
462
                        DBStoreParameters param;
463
                        int count = 0;
464
                        while (iter.hasNext()) {
465
                                param = (DBStoreParameters) iter.next();
466
                                lmodel.addElement(createTabeListItem(dbExplorer, param));
467
                                count++;
468
                        }
469

    
470
                        getTablesList().setModel(lmodel);
471
                        getTablesScrollPane().setViewportView(tablesList);
472
                        tablesScrollPane.updateUI();
473
                } catch (InitializeException e) {
474
                        logger.error("While getting table names: " + e.getMessage(), e);
475
                        NotificationManager.showMessageError("While getting table names: "
476
                                        + e.getMessage(), e);
477
                        return;
478
                } catch (DataException e) {
479
                        logger.error("While getting table names: " + e.getMessage(), e);
480
                        NotificationManager.showMessageError("While getting table names: "
481
                                        + e.getMessage(), e);
482
                        return;
483
                } catch (ValidateDataParametersException e) {
484
                        logger.error("While getting table names: " + e.getMessage(), e);
485
                        NotificationManager.showMessageError("While getting table names: "
486
                                        + e.getMessage(), e);
487
                        return;
488
                }
489
        }
490

    
491
        public void valueChanged(ListSelectionEvent arg0) {
492
                Object src = arg0.getSource();
493

    
494
                if (src == tablesList) {
495
                        TablesListItem selected = (TablesListItem) tablesList
496
                                        .getSelectedValue();
497

    
498
                        setSettingsPanels(selected);
499
                        checkFinishable();
500
                }
501
        }
502

    
503
        private boolean validFormSettings() {
504
                int count = tablesList.getModel().getSize();
505

    
506
                boolean at_least_one = false;
507
                boolean resp = true;
508

    
509
                for (int i = 0; i < count; i++) {
510
                        TablesListItem item = (TablesListItem) tablesList.getModel()
511
                                        .getElementAt(i);
512

    
513
                        if (item.isSelected()) {
514
                                at_least_one = true;
515
                        }
516

    
517
                        if (item.disturbsWizardValidity()) {
518
                                resp = false;
519
                        }
520
                }
521

    
522
                return (at_least_one && resp);
523
        }
524

    
525
        public void checkFinishable() {
526
                boolean finishable = validFormSettings();
527
                callStateChanged(finishable);
528
        }
529

    
530
        /**
531
         * This method initializes jdbcButton
532
         *
533
         * @return javax.swing.JButton
534
         */
535
        private JButton getJdbcButton() {
536
                if (dbButton == null) {
537
                        dbButton = new JButton();
538
                        dbButton.addActionListener(this);
539
                        dbButton.setToolTipText(PluginServices.getText(this,
540
                                        "add_connection"));
541
                        dbButton.setBounds(new java.awt.Rectangle(465, 20, 26, 21));
542

    
543
                        // FIXME use standard icon theme
544
                        String _file = createResourceUrl("images/jdbc.png").getFile();
545
                        dbButton.setIcon(new ImageIcon(_file));
546
                }
547

    
548
                return dbButton;
549
        }
550

    
551
        private void showConnectionErrorMessage(String _msg) {
552
                String msg = (_msg.length() > 300) ? "" : (": " + _msg);
553
                String title = PluginServices.getText(this, "connection_error");
554
                JOptionPane.showMessageDialog(this, title + msg, title,
555
                                JOptionPane.ERROR_MESSAGE);
556
        }
557

    
558
        private java.net.URL createResourceUrl(String path) {
559
                return getClass().getClassLoader().getResource(path);
560
        }
561

    
562
        public void setSettingsPanels(TablesListItem actTable) {
563
                if (actTable == null) {
564
                        setEmptyPanels();
565

    
566
                        return;
567
                }
568
                fieldsPanel = actTable.getUserSelectedFieldsPanel();
569

    
570
                removeFieldPanels();
571
                add(fieldsPanel);
572
                fieldsPanel.repaint();
573
                removeSettingsPanels();
574
                add(emptySettingsPanel);
575

    
576
                settingsPanel = createSettingsPanel(actTable);
577

    
578
                removeSettingsPanels();
579
                add(settingsPanel);
580
                settingsPanel.repaint();
581

    
582

    
583
                repaint();
584
        }
585

    
586

    
587

    
588
        protected UserTableSettingsPanel createSettingsPanel(TablesListItem actTable) {
589
                if (actTable == null) {
590
                        return new UserTableSettingsPanel(null, "", true, this, null);
591
                }
592

    
593
                return actTable.getUserTableSettingsPanel();
594
        }
595

    
596
        protected void setEmptyPanels() {
597
                removeFieldPanels();
598
                add(emptyFieldsPanel);
599
                fieldsPanel = emptyFieldsPanel;
600

    
601
                repaint();
602
        }
603

    
604
        private void removeFieldPanels() {
605
                for (int i = 0; i < getComponentCount(); i++) {
606
                        if (getComponent(i) instanceof UserSelectedFieldsPanel) {
607
                                remove(i);
608
                        }
609
                }
610
        }
611

    
612
        public DataStoreParameters[] getParameters() {
613
                try {
614
                        TablesListItem[] selected = getSelectedTables();
615
                        int count = selected.length;
616
                        DBStoreParameters[] dbParameters = new DBStoreParameters[count];
617

    
618
                        for (int i = 0; i < count; i++) {
619
                                TablesListItem item = selected[i];
620

    
621

    
622
                                dbParameters[i] = getParameterForTable(item);
623
                        }
624

    
625
                        return dbParameters;// layerArrayToGroup(all_layers, groupName);
626
                } catch (Exception e) {
627
                        logger.error("While creating jdbc layer: " + e.getMessage(), e);
628
                        NotificationManager.addError("Error al cargar la capa: "
629
                                        + e.getMessage(), e);
630
                }
631

    
632
                return null;
633
        }
634

    
635
        /**
636
         * This method process the errors found in a layer
637
         *
638
         * @param lyr
639
         * @param mapControl
640
         */
641

    
642
        protected void processErrorsOfLayer(FLayer lyr, MapControl mapControl) {
643
                // List errors = lyr.getErrors();
644
                // wp.callError(null);
645
                mapControl.getMapContext().callNewErrorEvent(null);
646
        }
647

    
648
        private void removeSettingsPanels() {
649
                for (int i = 0; i < getComponentCount(); i++) {
650
                        if (getComponent(i) instanceof UserTableSettingsPanel) {
651
                                remove(i);
652
                        }
653
                }
654
        }
655

    
656
        protected PrepareContext getPrepareDataStoreContext() {
657
                if (this.prepareDSContext == null) {
658
                        this.prepareDSContext = new PrepareContext() {
659
                                public Window getOwnerWindow() {
660
                                        return null;
661
                                }
662

    
663
                                public IProjection getViewProjection() {
664
                                        return null;
665
                                }
666

    
667
                        };
668
                }
669
                return this.prepareDSContext;
670
        }
671

    
672
        @Override
673
        public void close() {
674
                // Nothing to do
675
        }
676

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