Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.library / org.gvsig.exportto / org.gvsig.exportto.swing / org.gvsig.exportto.swing.prov / org.gvsig.exportto.swing.prov.jdbc / src / main / java / org / gvsig / exportto / swing / prov / jdbc / panel / SelectTableNamePanel.java @ 43377

History | View | Annotate | Download (16.2 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or modify it under
7
 * the terms of the GNU General Public License as published by the Free Software
8
 * Foundation; either version 3 of the License, or (at your option) any later
9
 * version.
10
 *
11
 * This program is distributed in the hope that it will be useful, but WITHOUT
12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14
 * details.
15
 *
16
 * You should have received a copy of the GNU General Public License along with
17
 * this program; if not, write to the Free Software Foundation, Inc., 51
18
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19
 *
20
 * For any additional information, do not hesitate to contact us at info AT
21
 * gvsig.com, or visit our website www.gvsig.com.
22
 */
23
package org.gvsig.exportto.swing.prov.jdbc.panel;
24

    
25
import java.awt.event.ActionEvent;
26
import java.awt.event.ActionListener;
27
import java.util.Iterator;
28
import java.util.List;
29
import java.util.logging.Level;
30

    
31
import javax.swing.DefaultListModel;
32
import javax.swing.JComponent;
33
import javax.swing.JOptionPane;
34
import javax.swing.ListModel;
35
import javax.swing.SwingUtilities;
36
import javax.swing.event.AncestorEvent;
37
import javax.swing.event.AncestorListener;
38
import org.apache.commons.lang3.StringUtils;
39
//import org.gvsig.app.ApplicationLocator;
40
//import org.gvsig.app.ApplicationManager;
41
import org.gvsig.exportto.swing.ExporttoSwingLocator;
42
import org.gvsig.exportto.swing.ExporttoSwingManager;
43
import org.gvsig.exportto.swing.prov.jdbc.ExporttoJDBCOptions;
44
import org.gvsig.exportto.swing.spi.ExporttoPanelValidationException;
45
import org.gvsig.exportto.swing.spi.ExporttoSwingProviderPanel;
46
import org.gvsig.fmap.dal.DALLocator;
47
import org.gvsig.fmap.dal.DataManager;
48
import org.gvsig.fmap.dal.SQLBuilder;
49
import org.gvsig.fmap.dal.exception.InitializeException;
50
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
51
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
52
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorer;
53
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParameters;
54
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
55
import org.gvsig.tools.ToolsLocator;
56
import org.gvsig.tools.i18n.I18nManager;
57
import org.gvsig.tools.swing.api.ToolsSwingLocator;
58
import org.gvsig.tools.swing.api.threadsafedialogs.ThreadSafeDialogsManager;
59
import org.gvsig.tools.task.AbstractMonitorableTask;
60
import org.gvsig.tools.task.SimpleTaskStatus;
61
import org.slf4j.Logger;
62
import org.slf4j.LoggerFactory;
63

    
64
/**
65
 * @author gvSIG Team
66
 * @version $Id$
67
 *
68
 */
69
public class SelectTableNamePanel extends SelectTableNamePanelLayout implements ExporttoSwingProviderPanel {
70

    
71
    private static final Logger logger = LoggerFactory.getLogger(SelectTableNamePanel.class);
72

    
73
    private static final long serialVersionUID = 6269512983586358017L;
74
    private final ExporttoJDBCOptions provider;
75

    
76
    private FillTablesListTask task = null;
77
    private SQLBuilder sqlbuilder;
78

    
79
    private static class TableItem {
80

    
81
        private JDBCStoreParameters params;
82
        private String label;
83

    
84
        public TableItem(String label, JDBCStoreParameters params) {
85
            this.params = params;
86
            this.label = label;
87
        }
88

    
89
        public TableItem(JDBCStoreParameters params) {
90
            this( StringUtils.isEmpty(params.getSchema())? 
91
                params.getTable() : params.getSchema() + "." + params.getTable(), 
92
                params);
93
        }
94

    
95
        @Override
96
        public String toString() {
97
            return this.label;
98
        }
99

    
100
        public JDBCStoreParameters getParams() {
101
            return this.params;
102
        }
103
    }
104

    
105
    public SelectTableNamePanel(ExporttoJDBCOptions provider) {
106
        this.provider = provider;
107
        initComponents();
108
        this.addAncestorListener(new AncestorListener() {
109

    
110
            @Override
111
            public void ancestorAdded(AncestorEvent ae) {
112
            }
113

    
114
            @Override
115
            public void ancestorRemoved(AncestorEvent ae) {
116
                cancelTask();
117
            }
118

    
119
            @Override
120
            public void ancestorMoved(AncestorEvent ae) {
121
            }
122
        });
123
    }
124

    
125
    private void initComponents() {
126
        this.rdoCreateTable.addActionListener(new ActionListener() {
127
            @Override
128
            public void actionPerformed(ActionEvent e) {
129
                onChangeRadioSelecion();
130
            }
131
        });
132
        this.rdoInsert.addActionListener(new ActionListener() {
133
            @Override
134
            public void actionPerformed(ActionEvent e) {
135
                onChangeRadioSelecion();
136
            }
137
        });
138
        this.rdoCreateTable.setSelected(true);
139
        this.rdoInsert.setEnabled(false);
140
        this.lstTables.setEnabled(false);
141
        try {
142
            this.txtTableName.setText(this.provider.getSource().getName());
143
        } catch (Exception ex) {
144
            logger.warn("Can't set the default value for the table name", ex);
145
        }
146

    
147
        I18nManager i18nManager = ToolsLocator.getI18nManager();
148
        this.lblHeader.setText(i18nManager.getTranslation("_Indique_donde_desea_insertar_los_datos"));
149
        this.lblWarningUseExistingTable.setText(
150
                "<html>\n"
151
                + i18nManager.getTranslation("_Los_datos_se_insertaran_usando_los_nombres_de_columna_que_coincidan_con_la_tabla_origen_dejandose_al_valor_por_defecto_para_los_que_no_haya_valores_en_la_tabla_origen")
152
                + "\n</html>"
153
        );
154
        this.rdoInsert.setText(i18nManager.getTranslation("_Insertar_registros_en_una_tabla_existente"));
155
        this.lblSelectTableName.setText(i18nManager.getTranslation("_Seleccione_la_tabla_a_usar"));
156
        this.rdoCreateTable.setText(i18nManager.getTranslation("_Crear_una_tabla_nueva"));
157
        this.lblSchema.setText(i18nManager.getTranslation("_Indique_el_esquema_en_el_que_desea_crear_la_tabla"));
158
        this.lblTableName.setText(i18nManager.getTranslation("_Indique_el_nombre_de_la_tabla"));
159
    }
160

    
161
    private void cancelTask() {
162
        if (task != null) {
163
            task.cancelRequest();
164
            task.getSimpleTaskStatus().remove();
165
            task = null;
166
        }
167
    }
168

    
169
    public boolean canCreateTable() {
170
        return this.rdoCreateTable.isSelected();
171
    }
172

    
173
    public String getSchema() {
174
        if (this.canCreateTable()) {
175
            return StringUtils.defaultIfBlank(this.txtSchema.getText(), null);
176
        }
177
        TableItem item = (TableItem) this.lstTables.getSelectedValue();
178
        JDBCStoreParameters tableParameter = item.getParams();
179
        if (tableParameter == null) {
180
            return null;
181
        }
182
        return tableParameter.getSchema();
183
    }
184

    
185
    public String getTableName() {
186
        if (this.canCreateTable()) {
187
            return StringUtils.defaultIfBlank(this.txtTableName.getText(), null);
188
        }
189
        TableItem item = (TableItem) this.lstTables.getSelectedValue();
190
        if (item == null) {
191
            return null;
192
        }
193
        JDBCStoreParameters tableParameter = item.getParams();
194

    
195
        if (tableParameter == null) {
196
            return null;
197
        }
198
        return tableParameter.getTable();
199
    }
200

    
201
    @Override
202
    public String getPanelTitle() {
203
        I18nManager i18nManager = ToolsLocator.getI18nManager();
204
        return i18nManager.getTranslation("_Tablename");
205
    }
206

    
207
    @Override
208
    public boolean isValidPanel() throws ExporttoPanelValidationException {
209
        I18nManager i18nManager = ToolsLocator.getI18nManager();
210
        String tablename = this.getTableName();
211
        if (tablename == null) {
212
            throw new ExporttoPanelValidationException(
213
                    i18nManager.getTranslation(
214
                            "_The_name_of_table_cannot_be_empty"
215
                    )
216
            );
217
        }
218
        String schema = this.getSchema();
219
        if( sqlbuilder.supportSchemas() ) {
220
            if (schema == null) {
221
                throw new ExporttoPanelValidationException(
222
                        i18nManager.getTranslation(
223
                                "_The_name_of_schema_cannot_be_empty"
224
                        )
225
                );
226
            }
227
        }
228
        if (this.rdoCreateTable.isSelected()) {
229
            String tablename_tr = tablename;
230
            if( this.provider.getTranslateIdentifiersToLowerCase() ) {
231
                tablename_tr = tablename_tr.toLowerCase();
232
            }
233
            if( this.provider.getTranslateHyphens()) {
234
                tablename_tr = tablename_tr.replace("-", "_");
235
            }
236
            if( this.provider.getRemoveSpacesInIdentifiers() ) {
237
                tablename_tr = StringUtils.normalizeSpace(tablename_tr).replace(" ", "_");
238
            }
239
            if( !tablename_tr.equals(tablename) ) {
240
                String msg = i18nManager.getTranslation(
241
                        "Ha_utilizado_espacios_en_blanco_o_mayusculas_en_el_nombre_de_la_tabla_Desea_que_se_corrija_de_forma_automatica"
242
                );
243
                ThreadSafeDialogsManager dialogs = ToolsSwingLocator.getThreadSafeDialogsManager();
244
                int resp = dialogs.confirmDialog(
245
                        msg, 
246
                        i18nManager.getTranslation("_Warning"),
247
                        JOptionPane.YES_NO_OPTION, 
248
                        JOptionPane.WARNING_MESSAGE,
249
                        "Exportto_Table_name_with_spaces_or_mixed_case"
250
                );
251
                if( resp != JOptionPane.YES_OPTION ) {
252
                    msg = i18nManager.getTranslation(
253
                            "El_nombre_de_tabla_contiene_caracteres no_validos"
254
                    );
255
                    throw new ExporttoPanelValidationException(msg);
256
                }
257
                tablename = tablename_tr;
258
                this.txtTableName.setText(tablename);
259
            }
260
            ListModel model = this.lstTables.getModel();
261
            for (int i = 0; i < model.getSize(); i++) {
262
                TableItem item = (TableItem) model.getElementAt(i);
263
                if ( StringUtils.equals(schema,item.getParams().getSchema())
264
                        && StringUtils.equals(tablename,item.getParams().getTable())) {
265
                    String msg = i18nManager.getTranslation(
266
                            "_La_tabla_{0}_{1}_ya_existe_en_la_base_de_datos_Seleccione_la_opcion_de_insertar_registros_en_una_tabla_existente_para_a?adir_los_datos_a_esta_o_indique_otro_nombre",
267
                            new String[]{schema, tablename}
268
                    );
269
                    throw new ExporttoPanelValidationException(msg);
270
                }
271
            }
272
        }
273
        return true;
274
    }
275

    
276
    @Override
277
    public void enterPanel() {
278
        JDBCServerExplorerParameters explorerParameters = provider.getExplorerParameters();
279
        if (explorerParameters != null) {
280
            try {
281
                DataManager dataManager = DALLocator.getDataManager();
282
                JDBCServerExplorer explorer = (JDBCServerExplorer) dataManager.openServerExplorer(
283
                    explorerParameters.getExplorerName(),
284
                    explorerParameters
285
                );
286
                this.sqlbuilder = explorer.createSQLBuilder();
287
            } catch (Exception ex) {
288
                throw new RuntimeException("Can't retrieve the sqlbuilder", ex);
289
            }
290
        }
291
        this.fillTablesList();
292
    }
293

    
294
    @Override
295
    public JComponent asJComponent() {
296
        return this;
297
    }
298

    
299
    public void onChangeRadioSelecion() {
300
        if (this.rdoCreateTable.isSelected()) {
301
            this.txtSchema.setEnabled(true);
302
            this.txtTableName.setEnabled(true);
303
            this.lstTables.setEnabled(false);
304
        } else {
305
            this.txtSchema.setEnabled(false);
306
            this.txtTableName.setEnabled(false);
307
            this.lstTables.setEnabled(true);
308
        }
309
    }
310

    
311
    private void fillTablesList() {
312

    
313
        JDBCServerExplorerParameters explorerParameters = this.provider.getExplorerParameters();
314
        if (explorerParameters == null) {
315
            return;
316
        }
317
        cancelTask();
318
        this.task = new FillTablesListTask();
319
        task.setDaemon(true);
320
        task.start();
321
    }
322

    
323
    private class FillTablesListTask extends AbstractMonitorableTask {
324

    
325
        public FillTablesListTask() {
326
            super("Export");
327
        }
328

    
329
        @Override
330
        protected SimpleTaskStatus getSimpleTaskStatus() {
331
            return (SimpleTaskStatus) this.getTaskStatus();
332
        }
333

    
334
        @Override
335
        public void run() {
336

    
337
            JDBCServerExplorerParameters explorerParameters = provider.getExplorerParameters();
338
            if (provider.getExplorerParameters() == null) {
339
                return;
340
            }
341
            final SimpleTaskStatus status = this.getSimpleTaskStatus();
342
            try {
343
                status.setAutoremove(true);
344

    
345
                DataManager dataManager = DALLocator.getDataManager();
346

    
347
                this.getSimpleTaskStatus().message("Connecting server");
348
                explorerParameters.setShowInformationDBTables(false);
349
                final JDBCServerExplorer explorer = (JDBCServerExplorer) dataManager.openServerExplorer(
350
                        explorerParameters.getExplorerName(),
351
                        explorerParameters
352
                );
353
                SwingUtilities.invokeAndWait(new Runnable() {
354

    
355
                    @Override
356
                    public void run() {
357
                        if( sqlbuilder.supportSchemas() ) {
358
                            txtSchema.setText(sqlbuilder.default_schema());
359
                        } else {
360
                            txtSchema.setText("");
361
                            txtSchema.setEnabled(false);
362
                        }
363
                    }
364
                });
365

    
366
                this.getSimpleTaskStatus().message("Retrieving tables");
367
                final List<JDBCStoreParameters> tables = explorer.list();
368

    
369
                this.getSimpleTaskStatus().message("Add tables");
370

    
371
                SwingUtilities.invokeAndWait(new Runnable() {
372
                    @Override
373
                    public void run() {
374
                        DefaultListModel lmodel = new DefaultListModel();
375
                        Iterator<JDBCStoreParameters> it = tables.iterator();
376
                        while (it.hasNext()) {
377
                            if (status.isCancelled()) {
378
                                status.cancel();
379
                                break;
380
                            }
381
                            JDBCStoreParameters table = it.next();
382
                            lmodel.addElement(new TableItem(table));
383
                        }
384
                        lstTables.setModel(lmodel);
385
                        //lstTables.setEnabled(true);
386
                        rdoInsert.setEnabled(true);
387
                    }
388
                });
389

    
390
                status.message("finish");
391
                status.terminate();
392

    
393
            } catch (final Exception ex) {
394
                logger.warn("Fail to fill tables list", ex);
395
                if (status.isCancellationRequested()) {
396
                    status.cancel();
397
                }
398
                if (status.isRunning()) {
399
                    try {
400
                        SwingUtilities.invokeAndWait(new Runnable() {
401
                            @Override
402
                            public void run() {
403
                                I18nManager i18nManager = ToolsLocator.getI18nManager();
404
                                ExporttoSwingManager manager = ExporttoSwingLocator.getSwingManager();
405

    
406
                                manager.showMessage(
407
                                        i18nManager.getTranslation("_Warning"),
408
                                        i18nManager.getTranslation("_There_have_been_problems_filling_data_in_panel")
409
                                        + " (" + getPanelTitle() + ")",
410
                                        ex,
411
                                        null
412
                                );
413
                            }
414
                        });
415
                    } catch (Exception ex2) {
416
                        logger.warn("Can't show error message", ex2);
417
                    }
418
                }
419
            } finally {
420
                status.terminate();
421
                status.remove();
422
            }
423

    
424
        }
425

    
426
    }
427

    
428
}