Statistics
| Revision:

root / branches / v2_0_0_prep / extensions / extGeoDB / src / org / gvsig / geodb / vectorialdb / wizard / WizardDB.java @ 33205

History | View | Annotate | Download (16.5 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

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

    
48
import org.gvsig.andami.PluginServices;
49
import org.gvsig.andami.messages.NotificationManager;
50
import org.gvsig.app.ApplicationLocator;
51
import org.gvsig.app.ApplicationManager;
52
import org.gvsig.app.gui.WizardPanel;
53
import org.gvsig.app.prepareAction.PrepareContext;
54
import org.gvsig.app.project.Project;
55
import org.gvsig.app.project.ProjectManager;
56
import org.gvsig.app.project.documents.table.TableDocument;
57
import org.gvsig.app.project.documents.table.TableManager;
58
import org.gvsig.fmap.dal.DALLocator;
59
import org.gvsig.fmap.dal.DataManager;
60
import org.gvsig.fmap.dal.DataStoreParameters;
61
import org.gvsig.fmap.dal.exception.DataException;
62
import org.gvsig.fmap.dal.exception.InitializeException;
63
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
64
import org.gvsig.fmap.dal.feature.FeatureStore;
65
import org.gvsig.fmap.dal.serverexplorer.db.DBServerExplorer;
66
import org.gvsig.fmap.dal.serverexplorer.db.DBServerExplorerParameters;
67
import org.gvsig.fmap.dal.store.db.DBStoreParameters;
68
import org.gvsig.fmap.mapcontext.layers.FLayer;
69
import org.gvsig.fmap.mapcontrol.MapControl;
70
import org.gvsig.geodb.SingleVectorialDBConnectionExtension;
71
import org.gvsig.gui.beans.swing.JButton;
72
import org.slf4j.Logger;
73
import org.slf4j.LoggerFactory;
74

    
75

    
76
public class WizardDB extends WizardPanel implements ActionListener,
77
                ListSelectionListener {
78

    
79
        private static final String WIZARD_TAB_NAME = "DB";
80
        private static Logger logger = LoggerFactory.getLogger(WizardDB.class
81
                        .getName());
82

    
83
    private JPanel namePanel = null;
84
        private JPanel tablesPanel = null;
85
        private JScrollPane tablesScrollPane = null;
86
        private AvailableTablesCheckBoxList tablesList = null;
87
        private JComboBox datasourceComboBox = null;
88
        private UserSelectedFieldsPanel fieldsPanel = null;
89
        private UserSelectedFieldsPanel emptyFieldsPanel = null;
90
        private JButton dbButton = null;
91
        private DBServerExplorerParameters dbExplorerParameters;
92

    
93
    private UserTableSettingsPanel settingsPanel = null;
94
        protected UserTableSettingsPanel emptySettingsPanel = null;
95
        private PrepareContext prepareDSContext;
96

    
97
    public WizardDB() {
98
                super();
99
                initialize();
100
        }
101

    
102

    
103
        protected void initialize() {
104
                setTabName(WIZARD_TAB_NAME);
105
                setLayout(null);
106
                setSize(512, 478);
107

    
108

    
109

    
110
                emptyFieldsPanel = new UserSelectedFieldsPanel(null, true, this);
111
                add(emptyFieldsPanel);
112

    
113
        add(getNamePanel(), null);
114
                loadVectorialDBDatasourcesCombo(null);
115

    
116
                add(getTablesPanel(), null);
117

    
118
        emptySettingsPanel = createSettingsPanel(null);
119
        add(emptySettingsPanel);
120

    
121
        }
122

    
123

    
124
    private void loadVectorialDBDatasourcesCombo(MyExplorer sel) {
125
                getDatasourceComboBox().removeAllItems();
126
                DataManager dm = DALLocator.getDataManager();
127
                List names = dm.getStoreProviders();
128
                if (sel != null) {
129
                        getDatasourceComboBox().addItem(sel);
130
                }
131

    
132
                if (names == null) {
133
                        return;
134
                }
135

    
136
        }
137

    
138
        public void initWizard() {
139
        }
140

    
141
        public void execute() {
142
                SingleVectorialDBConnectionExtension.saveAllToPersistence();
143

    
144
                TablesListItem[] tables = getSelectedTables();
145

    
146
                DataManager man = DALLocator.getDataManager();
147
                FeatureStore store, storeToAdd;
148

    
149
                String docName;
150
                TableDocument document;
151
//                Project project = ((ProjectExtension) PluginServices
152
//                                .getExtension(ProjectExtension.class)).getProject();
153
                Project project = ProjectManager.getInstance().getCurrentProject();
154

    
155
                ApplicationManager appGvSIGMan = ApplicationLocator.getManager();
156
                PrepareContext context = this.getPrepareDataStoreContext();
157
                DBStoreParameters storeParams;
158
                for (TablesListItem table : tables) {
159
                        storeParams = getParameterForTable(table);
160

    
161
                        try {
162
                                storeParams = (DBStoreParameters) appGvSIGMan
163
                                                .prepareOpenDataStoreParameters(storeParams, context);
164
                        } catch (Exception e2) {
165
                                NotificationManager.addError(e2);
166
                                continue;
167
                        }
168

    
169
                        UserTableSettingsPanel userTableSettingsPanel = table
170
                                        .getUserTableSettingsPanel();
171

    
172
                        docName = userTableSettingsPanel.getUserLayerName();
173
                        try {
174
                                store = (FeatureStore) man.createStore(storeParams);
175
                        } catch (Exception e) {
176
                                NotificationManager.addError(e);
177
                                return;
178
                        }
179

    
180
                        try {
181
                                storeToAdd = (FeatureStore) appGvSIGMan.pepareOpenDataSource(
182
                                                store, context);
183
                        } catch (Exception e) {
184
                                NotificationManager.addError(e);
185
                                store.dispose();
186
                                return;
187
                        }
188

    
189
                        
190
//                        document = ProjectFactory.createTable(docName, store);
191

    
192
                        document = (TableDocument) ProjectManager.getInstance().createDocument(TableManager.TYPENAME, docName);
193
                        document.setStore(store);
194
                        project.add(document);
195

    
196
                }
197

    
198
        }
199

    
200
        protected DBStoreParameters getParameterForTable(TablesListItem table) {
201
                DBStoreParameters parameters = table.getParameters();
202

    
203
                UserTableSettingsPanel userTableSettingsPanel = table
204
                                .getUserTableSettingsPanel();
205

    
206

    
207

    
208
                String fidField = userTableSettingsPanel.getIdFieldName();
209
                if (!(fidField.startsWith("{") && fidField.endsWith("}"))) {
210
                        parameters.setPkFields(new String[] { fidField });
211
                        fidField = null;
212
                }
213
                String[] fields = table.getUserSelectedFieldsPanel()
214
                                .getUserSelectedFields(fidField, null);
215

    
216
                if (userTableSettingsPanel.isSqlActive()) {
217
                        String whereClause = userTableSettingsPanel
218
                                        .getWhereClause();
219
                        parameters.setBaseFilter(whereClause);
220
                } else {
221
                        parameters.setBaseFilter("");
222
                }
223

    
224
                parameters.setFields(fields);
225

    
226

    
227
                return parameters;
228

    
229
        }
230

    
231
        protected TablesListItem[] getSelectedTables() {
232
                int count = tablesList.getModel().getSize();
233
                ArrayList resp = new ArrayList();
234

    
235
                for (int i = 0; i < count; i++) {
236
                        TablesListItem item = (TablesListItem) tablesList.getModel()
237
                                        .getElementAt(i);
238

    
239
                        if (item.isSelected()) {
240
                                resp.add(item);
241
                        }
242
                }
243

    
244
                return (TablesListItem[]) resp.toArray(new TablesListItem[0]);
245
        }
246

    
247
        /**
248
         * This method initializes namePanel
249
         *
250
         * @return javax.swing.JPanel
251
         */
252
        private JPanel getNamePanel() {
253
                if (namePanel == null) {
254
                        namePanel = new JPanel();
255
                        namePanel.setLayout(null);
256
                        namePanel.setBounds(new java.awt.Rectangle(5, 5, 501, 51));
257
                        namePanel.setBorder(javax.swing.BorderFactory.createTitledBorder(
258
                                        null, PluginServices.getText(this, "choose_connection"),
259
                                        javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
260
                                        javax.swing.border.TitledBorder.DEFAULT_POSITION, null,
261
                                        null));
262
                        namePanel.add(getDatasourceComboBox(), null);
263
                        namePanel.add(getJdbcButton(), null);
264
                }
265

    
266
                return namePanel;
267
        }
268

    
269
        /**
270
         * This method initializes tablesPanel
271
         *
272
         * @return javax.swing.JPanel
273
         */
274
        private JPanel getTablesPanel() {
275
                if (tablesPanel == null) {
276
                        tablesPanel = new JPanel();
277
                        tablesPanel.setLayout(new BorderLayout());
278
                        tablesPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(
279
                                        null, PluginServices.getText(this, "choose_table"),
280
                                        javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
281
                                        javax.swing.border.TitledBorder.DEFAULT_POSITION, null,
282
                                        null));
283
                        tablesPanel.setBounds(new java.awt.Rectangle(5, 55, 246, 166));
284
                        tablesPanel
285
                                        .add(getTablesScrollPane(), java.awt.BorderLayout.CENTER);
286
                }
287

    
288
                return tablesPanel;
289
        }
290

    
291
        /**
292
         * This method initializes settingsPanel
293
         *
294
         * @return javax.swing.JPanel
295
         */
296

    
297
        /**
298
         * This method initializes tablesScrollPane
299
         *
300
         * @return javax.swing.JScrollPane
301
         */
302
        private JScrollPane getTablesScrollPane() {
303
                if (tablesScrollPane == null) {
304
                        tablesScrollPane = new JScrollPane();
305
                        tablesScrollPane.setViewportView(getTablesList());
306
                }
307

    
308
                return tablesScrollPane;
309
        }
310

    
311
        /**
312
         * This method initializes tablesList
313
         *
314
         * @return javax.swing.JList
315
         */
316
        protected AvailableTablesCheckBoxList getTablesList() {
317
                if (tablesList == null) {
318
                        tablesList = new AvailableTablesCheckBoxList(this);
319
                        tablesList.addListSelectionListener(this);
320
                        tablesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
321
                }
322

    
323
                return tablesList;
324
        }
325

    
326
        /**
327
         * This method initializes layerNameTextField
328
         *
329
         * @return javax.swing.JTextField
330
         */
331

    
332
        /**
333
         * This method initializes jComboBox
334
         *
335
         * @return javax.swing.JComboBox
336
         */
337
        private JComboBox getDatasourceComboBox() {
338
                if (datasourceComboBox == null) {
339
                        datasourceComboBox = new JComboBox();
340
                        datasourceComboBox
341
                                        .setBounds(new java.awt.Rectangle(10, 20, 446, 21));
342
                        datasourceComboBox.addActionListener(this);
343
                }
344

    
345
                return datasourceComboBox;
346
        }
347

    
348
        public void actionPerformed(ActionEvent arg0) {
349
                if (datasourceComboBox.getItemCount() == 0) {
350
                        setEmptyPanels();
351
                }
352
                Object src = arg0.getSource();
353

    
354
                if (src == datasourceComboBox) {
355
                        Object sel_obj = datasourceComboBox.getSelectedItem();
356

    
357
                        if (sel_obj == null) {
358
                                return;
359
                        }
360
                        getDatasourceComboBox().repaint();
361
                        return;
362
                }
363

    
364
                if (src == dbButton) {
365
                        MyExplorer sel = addNewConnection();
366

    
367
                        if (sel != null) {
368
                                dbExplorerParameters = sel.getDbSeverExplorerParameters();
369
                                loadVectorialDBDatasourcesCombo(sel);
370
                                getDatasourceComboBox().setSelectedItem(sel);
371

    
372
                        }
373
                        updateTableList(dbExplorerParameters);
374
                }
375
        }
376

    
377
        private MyExplorer addNewConnection() {
378
                MyExplorer myExplorer = new MyExplorer();
379
                DBServerExplorerParameters resp = null;
380

    
381
                VectorialDBConnectionParamsDialog newco = new VectorialDBConnectionParamsDialog();
382
                newco.showDialog();
383

    
384
                if (newco.isOkPressed()) {
385
                        try {
386
                                resp = newco.getParameters();
387
                        } catch (Exception e) {
388
                                showConnectionErrorMessage(e.getMessage());
389
                                return null;
390
                        }
391
                        SingleVectorialDBConnectionExtension.saveAllToPersistence();
392
                        myExplorer.setDbExplorerParameters(resp);
393
                        myExplorer.setName(newco.getConnectionName());
394
                        return myExplorer;
395
                } else {
396
                        return null;
397
                }
398
        }
399

    
400
        protected TablesListItem createTabeListItem(DBServerExplorer dbExplorer,
401
                        DBStoreParameters param) {
402
                return new TablesListItem(dbExplorer, param, this);
403
        }
404

    
405
        private void updateTableList(
406
                        DBServerExplorerParameters dbSeverExplorerParameters2) {
407
                if (dbSeverExplorerParameters2 == null) {
408
                        return;
409
                }
410
                DataManager dm = DALLocator.getDataManager();
411
                DBServerExplorer dbExplorer;
412
                try {
413
                        dbExplorer = (DBServerExplorer) dm
414
                                        .createServerExplorer(dbSeverExplorerParameters2);
415

    
416
                        // TODO: use the mode to filter tables with geometries when opening
417
                        // a view document
418
                        List parameters = dbExplorer.list();
419

    
420
                        DefaultListModel lmodel = new DefaultListModel();
421

    
422
                        Iterator iter = parameters.iterator();
423
                        DBStoreParameters param;
424
                        while (iter.hasNext()) {
425
                                param = (DBStoreParameters) iter.next();
426
                                lmodel.addElement(createTabeListItem(dbExplorer, param));
427
                        }
428

    
429
                        getTablesList().setModel(lmodel);
430
                        getTablesScrollPane().setViewportView(tablesList);
431
                        tablesScrollPane.updateUI();
432
                } catch (InitializeException e) {
433
                        logger.error("While getting table names: " + e.getMessage(), e);
434
                        NotificationManager.showMessageError("While getting table names: "
435
                                        + e.getMessage(), e);
436
                        return;
437
                } catch (DataException e) {
438
                        logger.error("While getting table names: " + e.getMessage(), e);
439
                        NotificationManager.showMessageError("While getting table names: "
440
                                        + e.getMessage(), e);
441
                        return;
442
                } catch (ValidateDataParametersException e) {
443
                        logger.error("While getting table names: " + e.getMessage(), e);
444
                        NotificationManager.showMessageError("While getting table names: "
445
                                        + e.getMessage(), e);
446
                        return;
447
                }
448
        }
449

    
450
        public void valueChanged(ListSelectionEvent arg0) {
451
                Object src = arg0.getSource();
452

    
453
                if (src == tablesList) {
454
                        TablesListItem selected = (TablesListItem) tablesList
455
                                        .getSelectedValue();
456

    
457
                        setSettingsPanels(selected);
458
                        checkFinishable();
459
                }
460
        }
461

    
462
        private boolean validFormSettings() {
463
                int count = tablesList.getModel().getSize();
464

    
465
                boolean at_least_one = false;
466
                boolean resp = true;
467

    
468
                for (int i = 0; i < count; i++) {
469
                        TablesListItem item = (TablesListItem) tablesList.getModel()
470
                                        .getElementAt(i);
471

    
472
                        if (item.isSelected()) {
473
                                at_least_one = true;
474
                        }
475

    
476
                        if (item.disturbsWizardValidity()) {
477
                                resp = false;
478
                        }
479
                }
480

    
481
                return (at_least_one && resp);
482
        }
483

    
484
        public void checkFinishable() {
485
                boolean finishable = validFormSettings();
486
                callStateChanged(finishable);
487
        }
488

    
489
        /**
490
         * This method initializes jdbcButton
491
         *
492
         * @return javax.swing.JButton
493
         */
494
        private JButton getJdbcButton() {
495
                if (dbButton == null) {
496
                        dbButton = new JButton();
497
                        dbButton.addActionListener(this);
498
                        dbButton.setToolTipText(PluginServices.getText(this,
499
                                        "add_connection"));
500
                        dbButton.setBounds(new java.awt.Rectangle(465, 20, 26, 21));
501

    
502
                        // FIXME use standard icon theme
503
                        String _file = createResourceUrl("images/jdbc.png").getFile();
504
                        dbButton.setIcon(new ImageIcon(_file));
505
                }
506

    
507
                return dbButton;
508
        }
509

    
510
        private void showConnectionErrorMessage(String _msg) {
511
                String msg = (_msg.length() > 300) ? "" : (": " + _msg);
512
                String title = PluginServices.getText(this, "connection_error");
513
                JOptionPane.showMessageDialog(this, title + msg, title,
514
                                JOptionPane.ERROR_MESSAGE);
515
        }
516

    
517
        private java.net.URL createResourceUrl(String path) {
518
                return getClass().getClassLoader().getResource(path);
519
        }
520

    
521
        public void setSettingsPanels(TablesListItem actTable) {
522
                if (actTable == null) {
523
                        setEmptyPanels();
524

    
525
                        return;
526
                }
527
                fieldsPanel = actTable.getUserSelectedFieldsPanel();
528

    
529
                removeFieldPanels();
530
                add(fieldsPanel);
531
                fieldsPanel.repaint();
532
                removeSettingsPanels();
533
                add(emptySettingsPanel);
534

    
535
                settingsPanel = createSettingsPanel(actTable);
536

    
537
                removeSettingsPanels();
538
                add(settingsPanel);
539
                settingsPanel.repaint();
540

    
541

    
542
                repaint();
543
        }
544

    
545

    
546

    
547
        protected UserTableSettingsPanel createSettingsPanel(TablesListItem actTable) {
548
                if (actTable == null) {
549
                        return new UserTableSettingsPanel(null, "", true, this, null);
550
                }
551

    
552
                return actTable.getUserTableSettingsPanel();
553
        }
554

    
555
        protected void setEmptyPanels() {
556
                removeFieldPanels();
557
                add(emptyFieldsPanel);
558
                fieldsPanel = emptyFieldsPanel;
559

    
560
                repaint();
561
        }
562

    
563
        private void removeFieldPanels() {
564
                for (int i = 0; i < getComponentCount(); i++) {
565
                        if (getComponent(i) instanceof UserSelectedFieldsPanel) {
566
                                remove(i);
567
                        }
568
                }
569
        }
570

    
571
        public DataStoreParameters[] getParameters() {
572
                try {
573
                        TablesListItem[] selected = getSelectedTables();
574
                        int count = selected.length;
575
                        DBStoreParameters[] dbParameters = new DBStoreParameters[count];
576

    
577
                        for (int i = 0; i < count; i++) {
578
                                TablesListItem item = selected[i];
579

    
580

    
581
                                dbParameters[i] = getParameterForTable(item);
582
                        }
583

    
584
                        return dbParameters;// layerArrayToGroup(all_layers, groupName);
585
                } catch (Exception e) {
586
                        logger.error("While creating jdbc layer: " + e.getMessage(), e);
587
                        NotificationManager.addError("Error al cargar la capa: "
588
                                        + e.getMessage(), e);
589
                }
590

    
591
                return null;
592
        }
593

    
594
        /**
595
         * This method process the errors found in a layer
596
         *
597
         * @param lyr
598
         * @param mapControl
599
         */
600

    
601
        protected void processErrorsOfLayer(FLayer lyr, MapControl mapControl) {
602
                // List errors = lyr.getErrors();
603
                // wp.callError(null);
604
                mapControl.getMapContext().callNewErrorEvent(null);
605
        }
606

    
607
        private void removeSettingsPanels() {
608
                for (int i = 0; i < getComponentCount(); i++) {
609
                        if (getComponent(i) instanceof UserTableSettingsPanel) {
610
                                remove(i);
611
                        }
612
                }
613
        }
614

    
615
        protected PrepareContext getPrepareDataStoreContext() {
616
                if (this.prepareDSContext == null) {
617
                        this.prepareDSContext = new PrepareContext() {
618
                                public Window getOwnerWindow() {
619
                                        return null;
620
                                }
621

    
622
                        };
623
                }
624
                return this.prepareDSContext;
625
        }
626

    
627
        @Override
628
        public void close() {
629
                // Nothing to do
630
        }
631

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