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 @ 43637

History | View | Annotate | Download (16.3 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
                tablename_tr = tablename_tr.replace(".", "_");                
236
            }
237
            if( this.provider.getRemoveSpacesInIdentifiers() ) {
238
                tablename_tr = StringUtils.normalizeSpace(tablename_tr).replace(" ", "_");
239
            }
240
            if( !tablename_tr.equals(tablename) ) {
241
                String msg = i18nManager.getTranslation(
242
                        "Ha_utilizado_espacios_en_blanco_o_mayusculas_en_el_nombre_de_la_tabla_Desea_que_se_corrija_de_forma_automatica"
243
                );
244
                ThreadSafeDialogsManager dialogs = ToolsSwingLocator.getThreadSafeDialogsManager();
245
                int resp = dialogs.confirmDialog(
246
                        msg, 
247
                        i18nManager.getTranslation("_Warning"),
248
                        JOptionPane.YES_NO_OPTION, 
249
                        JOptionPane.WARNING_MESSAGE,
250
                        "Exportto_Table_name_with_spaces_or_mixed_case"
251
                );
252
                if( resp != JOptionPane.YES_OPTION ) {
253
                    msg = i18nManager.getTranslation(
254
                            "El_nombre_de_tabla_contiene_caracteres no_validos"
255
                    );
256
                    throw new ExporttoPanelValidationException(msg);
257
                }
258
                tablename = tablename_tr;
259
                this.txtTableName.setText(tablename);
260
            }
261
            ListModel model = this.lstTables.getModel();
262
            for (int i = 0; i < model.getSize(); i++) {
263
                TableItem item = (TableItem) model.getElementAt(i);
264
                if ( StringUtils.equals(schema,item.getParams().getSchema())
265
                        && StringUtils.equals(tablename,item.getParams().getTable())) {
266
                    String msg = i18nManager.getTranslation(
267
                            "_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",
268
                            new String[]{schema, tablename}
269
                    );
270
                    throw new ExporttoPanelValidationException(msg);
271
                }
272
            }
273
        }
274
        return true;
275
    }
276

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

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

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

    
312
    private void fillTablesList() {
313

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

    
324
    private class FillTablesListTask extends AbstractMonitorableTask {
325

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

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

    
335
        @Override
336
        public void run() {
337

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

    
346
                DataManager dataManager = DALLocator.getDataManager();
347

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

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

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

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

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

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

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

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

    
425
        }
426

    
427
    }
428

    
429
}