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

History | View | Annotate | Download (15.8 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.task.AbstractMonitorableTask;
58
import org.gvsig.tools.task.SimpleTaskStatus;
59
import org.slf4j.Logger;
60
import org.slf4j.LoggerFactory;
61

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

    
69
    private static final Logger logger = LoggerFactory.getLogger(SelectTableNamePanel.class);
70

    
71
    private static final long serialVersionUID = 6269512983586358017L;
72
    private final ExporttoJDBCOptions provider;
73

    
74
    private FillTablesListTask task = null;
75
    private SQLBuilder sqlbuilder;
76

    
77
    private static class TableItem {
78

    
79
        private JDBCStoreParameters params;
80
        private String label;
81

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

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

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

    
98
        public JDBCStoreParameters getParams() {
99
            return this.params;
100
        }
101
    }
102

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

    
108
            @Override
109
            public void ancestorAdded(AncestorEvent ae) {
110
            }
111

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

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

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

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

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

    
167
    public boolean canCreateTable() {
168
        return this.rdoCreateTable.isSelected();
169
    }
170

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

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

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

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

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

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

    
288
    @Override
289
    public JComponent asJComponent() {
290
        return this;
291
    }
292

    
293
    public void onChangeRadioSelecion() {
294
        if (this.rdoCreateTable.isSelected()) {
295
            this.txtSchema.setEnabled(true);
296
            this.txtTableName.setEnabled(true);
297
            this.lstTables.setEnabled(false);
298
        } else {
299
            this.txtSchema.setEnabled(false);
300
            this.txtTableName.setEnabled(false);
301
            this.lstTables.setEnabled(true);
302
        }
303
    }
304

    
305
    private void fillTablesList() {
306

    
307
        JDBCServerExplorerParameters explorerParameters = this.provider.getExplorerParameters();
308
        if (explorerParameters == null) {
309
            return;
310
        }
311
        cancelTask();
312
        this.task = new FillTablesListTask();
313
        task.setDaemon(true);
314
        task.start();
315
    }
316

    
317
    private class FillTablesListTask extends AbstractMonitorableTask {
318

    
319
        public FillTablesListTask() {
320
            super("Export");
321
        }
322

    
323
        @Override
324
        protected SimpleTaskStatus getSimpleTaskStatus() {
325
            return (SimpleTaskStatus) this.getTaskStatus();
326
        }
327

    
328
        @Override
329
        public void run() {
330

    
331
            JDBCServerExplorerParameters explorerParameters = provider.getExplorerParameters();
332
            if (provider.getExplorerParameters() == null) {
333
                return;
334
            }
335
            final SimpleTaskStatus status = this.getSimpleTaskStatus();
336
            try {
337
                status.setAutoremove(true);
338

    
339
                DataManager dataManager = DALLocator.getDataManager();
340

    
341
                this.getSimpleTaskStatus().message("Connecting server");
342
                explorerParameters.setShowInformationDBTables(false);
343
                final JDBCServerExplorer explorer = (JDBCServerExplorer) dataManager.openServerExplorer(
344
                        explorerParameters.getExplorerName(),
345
                        explorerParameters
346
                );
347
                SwingUtilities.invokeAndWait(new Runnable() {
348

    
349
                    @Override
350
                    public void run() {
351
                        if( sqlbuilder.supportSchemas() ) {
352
                            txtSchema.setText(sqlbuilder.default_schema());
353
                        } else {
354
                            txtSchema.setText("");
355
                            txtSchema.setEnabled(false);
356
                        }
357
                    }
358
                });
359

    
360
                this.getSimpleTaskStatus().message("Retrieving tables");
361
                final List<JDBCStoreParameters> tables = explorer.list();
362

    
363
                this.getSimpleTaskStatus().message("Add tables");
364

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

    
384
                status.message("finish");
385
                status.terminate();
386

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

    
400
                                manager.showMessage(
401
                                        i18nManager.getTranslation("_Warning"),
402
                                        i18nManager.getTranslation("_There_have_been_problems_filling_data_in_panel")
403
                                        + " (" + getPanelTitle() + ")",
404
                                        ex,
405
                                        null
406
                                );
407
                            }
408
                        });
409
                    } catch (Exception ex2) {
410
                        logger.warn("Can't show error message", ex2);
411
                    }
412
                }
413
            } finally {
414
                status.terminate();
415
                status.remove();
416
            }
417

    
418
        }
419

    
420
    }
421

    
422
}