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

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

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

    
57
/**
58
 * @author gvSIG Team
59
 * @version $Id$
60
 *
61
 */
62
public class SelectTableNamePanel extends SelectTableNamePanelLayout implements ExporttoSwingProviderPanel {
63

    
64
    private static final Logger logger = LoggerFactory.getLogger(SelectTableNamePanel.class);
65

    
66
    private static final long serialVersionUID = 6269512983586358017L;
67
    private final ExporttoJDBCOptions provider;
68

    
69
    private FillTablesListTask task = null;
70

    
71
    private static class TableItem {
72

    
73
        private JDBCStoreParameters params;
74
        private String label;
75

    
76
        public TableItem(String label, JDBCStoreParameters params) {
77
            this.params = params;
78
            this.label = label;
79
        }
80

    
81
        public TableItem(JDBCStoreParameters params) {
82
            this(params.getSchema() + "." + params.getTable(), params);
83
        }
84

    
85
        @Override
86
        public String toString() {
87
            return this.label;
88
        }
89

    
90
        public JDBCStoreParameters getParams() {
91
            return this.params;
92
        }
93
    }
94

    
95
    public SelectTableNamePanel(ExporttoJDBCOptions provider) {
96
        this.provider = provider;
97
        initComponents();
98
        this.addAncestorListener(new AncestorListener() {
99

    
100
            @Override
101
            public void ancestorAdded(AncestorEvent ae) {
102
            }
103

    
104
            @Override
105
            public void ancestorRemoved(AncestorEvent ae) {
106
                cancelTask();
107
            }
108

    
109
            @Override
110
            public void ancestorMoved(AncestorEvent ae) {
111
            }
112
        });
113
    }
114

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

    
137
        I18nManager i18nManager = ToolsLocator.getI18nManager();
138
        this.lblHeader.setText(i18nManager.getTranslation("_Indique_donde_desea_insertar_los_datos"));
139
        this.lblWarningUseExistingTable.setText(
140
                "<html>\n"
141
                + 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")
142
                + "\n</html>"
143
        );
144
        this.rdoInsert.setText(i18nManager.getTranslation("_Insertar_registros_en_una_tabla_existente"));
145
        this.lblSelectTableName.setText(i18nManager.getTranslation("_Seleccione_la_tabla_a_usar"));
146
        this.rdoCreateTable.setText(i18nManager.getTranslation("_Crear_una_tabla_nueva"));
147
        this.lblSchema.setText(i18nManager.getTranslation("_Indique_el_esquema_en_el_que_desea_crear_la_tabla"));
148
        this.lblTableName.setText(i18nManager.getTranslation("_Indique_el_nombre_de_la_tabla"));
149
    }
150

    
151
    private void cancelTask() {
152
        if (task != null) {
153
            task.cancelRequest();
154
            task.getSimpleTaskStatus().remove();
155
            task = null;
156
        }
157
    }
158

    
159
    public boolean canCreateTable() {
160
        return this.rdoCreateTable.isSelected();
161
    }
162

    
163
    public String getSchema() {
164
        if (this.canCreateTable()) {
165
            return StringUtils.defaultIfBlank(this.txtSchema.getText(), null);
166
        }
167
        TableItem item = (TableItem) this.lstTables.getSelectedValue();
168
        JDBCStoreParameters tableParameter = item.getParams();
169
        if (tableParameter == null) {
170
            return null;
171
        }
172
        return tableParameter.getSchema();
173
    }
174

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

    
185
        if (tableParameter == null) {
186
            return null;
187
        }
188
        return tableParameter.getTable();
189
    }
190

    
191
    @Override
192
    public String getPanelTitle() {
193
        I18nManager i18nManager = ToolsLocator.getI18nManager();
194
        return i18nManager.getTranslation("_Tablename");
195
    }
196

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

    
260
    @Override
261
    public void enterPanel() {
262
        this.fillTablesList();
263
    }
264

    
265
    @Override
266
    public JComponent asJComponent() {
267
        return this;
268
    }
269

    
270
    public void onChangeRadioSelecion() {
271
        if (this.rdoCreateTable.isSelected()) {
272
            this.txtSchema.setEnabled(true);
273
            this.txtTableName.setEnabled(true);
274
            this.lstTables.setEnabled(false);
275
        } else {
276
            this.txtSchema.setEnabled(false);
277
            this.txtTableName.setEnabled(false);
278
            this.lstTables.setEnabled(true);
279
        }
280
    }
281

    
282
    private void fillTablesList() {
283

    
284
        JDBCServerExplorerParameters explorerParameters = this.provider.getExplorerParameters();
285
        if (explorerParameters == null) {
286
            return;
287
        }
288
        cancelTask();
289
        this.task = new FillTablesListTask();
290
        task.setDaemon(true);
291
        task.start();
292
    }
293

    
294
    private class FillTablesListTask extends AbstractMonitorableTask {
295

    
296
        public FillTablesListTask() {
297
            super("Export");
298
        }
299

    
300
        @Override
301
        protected SimpleTaskStatus getSimpleTaskStatus() {
302
            return (SimpleTaskStatus) this.getTaskStatus();
303
        }
304

    
305
        @Override
306
        public void run() {
307

    
308
            JDBCServerExplorerParameters explorerParameters = provider.getExplorerParameters();
309
            if (provider.getExplorerParameters() == null) {
310
                return;
311
            }
312
            final SimpleTaskStatus status = this.getSimpleTaskStatus();
313
            try {
314
                status.setAutoremove(true);
315

    
316
                DataManager dataManager = DALLocator.getDataManager();
317

    
318
                this.getSimpleTaskStatus().message("Connecting server");
319
                explorerParameters.setShowInformationDBTables(false);
320
                final JDBCServerExplorer explorer = (JDBCServerExplorer) dataManager.openServerExplorer(
321
                        explorerParameters.getExplorerName(),
322
                        explorerParameters
323
                );
324
                SwingUtilities.invokeAndWait(new Runnable() {
325

    
326
                    @Override
327
                    public void run() {
328
                        txtSchema.setText(explorer.createSQLBuilder().default_schema());
329
                    }
330
                });
331

    
332
                this.getSimpleTaskStatus().message("Retrieving tables");
333
                final List<JDBCStoreParameters> tables = explorer.list();
334

    
335
                this.getSimpleTaskStatus().message("Add tables");
336

    
337
                SwingUtilities.invokeAndWait(new Runnable() {
338
                    @Override
339
                    public void run() {
340
                        DefaultListModel lmodel = new DefaultListModel();
341
                        Iterator<JDBCStoreParameters> it = tables.iterator();
342
                        while (it.hasNext()) {
343
                            if (status.isCancelled()) {
344
                                status.cancel();
345
                                break;
346
                            }
347
                            JDBCStoreParameters table = it.next();
348
                            lmodel.addElement(new TableItem(table));
349
                        }
350
                        lstTables.setModel(lmodel);
351
                        //lstTables.setEnabled(true);
352
                        rdoInsert.setEnabled(true);
353
                    }
354
                });
355

    
356
                status.message("finish");
357
                status.terminate();
358

    
359
            } catch (final Exception ex) {
360
                logger.warn("Fail to fill tables list", ex);
361
                if (status.isCancellationRequested()) {
362
                    status.cancel();
363
                }
364
                if (status.isRunning()) {
365
                    try {
366
                        SwingUtilities.invokeAndWait(new Runnable() {
367
                            @Override
368
                            public void run() {
369
                                I18nManager i18nManager = ToolsLocator.getI18nManager();
370
                                ExporttoSwingManager manager = ExporttoSwingLocator.getSwingManager();
371

    
372
                                manager.showMessage(
373
                                        i18nManager.getTranslation("_Warning"),
374
                                        i18nManager.getTranslation("_There_have_been_problems_filling_data_in_panel")
375
                                        + " (" + getPanelTitle() + ")",
376
                                        ex,
377
                                        null
378
                                );
379
                            }
380
                        });
381
                    } catch (Exception ex2) {
382
                        logger.warn("Can't show error message", ex2);
383
                    }
384
                }
385
            } finally {
386
                status.terminate();
387
                status.remove();
388
            }
389

    
390
        }
391

    
392
    }
393

    
394
}