Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.compat.cdc / org.gvsig.fmap.dal / org.gvsig.fmap.dal.swing / org.gvsig.fmap.dal.swing.impl / src / main / java / org / gvsig / fmap / dal / swing / impl / featurequery / DefaultFeatureQueryCalculatedColumnsPanel.java @ 46978

History | View | Annotate | Download (33.5 KB)

1
package org.gvsig.fmap.dal.swing.impl.featurequery;
2

    
3
import java.awt.Dimension;
4
import java.awt.event.ActionEvent;
5
import java.awt.event.ActionListener;
6
import java.net.URL;
7
import java.util.List;
8
import java.util.logging.Level;
9
import javax.swing.DefaultListModel;
10
import javax.swing.DefaultListSelectionModel;
11
import javax.swing.ImageIcon;
12
import javax.swing.JButton;
13
import javax.swing.JComboBox;
14
import javax.swing.JComponent;
15
import javax.swing.JList;
16
import javax.swing.JOptionPane;
17
import javax.swing.ListModel;
18
import javax.swing.ListSelectionModel;
19
import javax.swing.event.ChangeEvent;
20
import javax.swing.event.ChangeListener;
21
import javax.swing.event.DocumentEvent;
22
import javax.swing.event.DocumentListener;
23
import javax.swing.event.ListSelectionEvent;
24
import javax.swing.text.JTextComponent;
25
import org.apache.commons.io.FilenameUtils;
26
import org.apache.commons.lang.StringUtils;
27
import org.gvsig.configurableactions.ConfigurableActionsMamager;
28
import org.gvsig.expressionevaluator.Expression;
29
import org.gvsig.expressionevaluator.swing.ExpressionEvaluatorSwingLocator;
30
import org.gvsig.expressionevaluator.swing.ExpressionEvaluatorSwingManager;
31
import org.gvsig.expressionevaluator.swing.ExpressionPickerController;
32
import org.gvsig.fmap.dal.DALLocator;
33
import org.gvsig.fmap.dal.exception.DataException;
34
import org.gvsig.fmap.dal.expressionevaluator.FeatureAttributeEmulatorExpression;
35
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
36
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
37
import org.gvsig.fmap.dal.feature.FeatureQuery;
38
import org.gvsig.fmap.dal.feature.FeatureStore;
39
import org.gvsig.fmap.dal.feature.FeatureType;
40
import org.gvsig.fmap.dal.swing.DALSwingLocator;
41
import org.gvsig.fmap.dal.swing.featurequery.FeatureQueryCalculatedColumnsPanel;
42
import org.gvsig.fmap.dal.swing.featuretype.FeatureTypeAttributePanel;
43
import org.gvsig.fmap.dal.swing.featuretype.FeatureTypePanel;
44
import static org.gvsig.fmap.dal.swing.impl.DefaultDALSwingLibrary.LIBRARY_NAME;
45
import org.gvsig.fmap.dal.swing.impl.expressionevaluator.FeatureStoreElementFactory;
46
import org.gvsig.tools.ToolsLocator;
47
import org.gvsig.tools.dataTypes.Coercion;
48
import org.gvsig.tools.dataTypes.CoercionException;
49
import org.gvsig.tools.dataTypes.DataType;
50
import org.gvsig.tools.dataTypes.DataTypes;
51
import org.gvsig.tools.i18n.I18nManager;
52
import org.gvsig.tools.locator.ReferenceNotRegisteredException;
53
import org.gvsig.tools.swing.api.ListElement;
54
import org.gvsig.tools.swing.api.ToolsSwingLocator;
55
import org.gvsig.tools.swing.api.ToolsSwingManager;
56
import org.gvsig.tools.swing.api.ToolsSwingUtils;
57
import org.gvsig.tools.swing.api.pickercontroller.DataTypePickerController;
58
import org.gvsig.tools.swing.api.threadsafedialogs.ThreadSafeDialogsManager;
59
import org.gvsig.tools.swing.api.windowmanager.Dialog;
60
import org.gvsig.tools.swing.api.windowmanager.WindowManager;
61
import org.gvsig.tools.swing.api.windowmanager.WindowManager_v2;
62
import org.gvsig.tools.swing.icontheme.IconTheme;
63
import org.gvsig.tools.util.ToolsUtilLocator;
64
import org.slf4j.Logger;
65
import org.slf4j.LoggerFactory;
66

    
67
/**
68
 *
69
 * @author jjdelcerro
70
 */
71
public class DefaultFeatureQueryCalculatedColumnsPanel
72
        extends DefaultFeatureQueryCalculatedColumnsPanelView
73
        implements FeatureQueryCalculatedColumnsPanel {
74
    
75
    private class AttributeListElement extends ListElement<FeatureAttributeDescriptor> {
76
        
77
        public AttributeListElement(FeatureAttributeDescriptor value) {
78
            super(value.getLabel(), value);
79
        }
80
        
81
        @Override
82
        public String getLabel() {
83
            return ((FeatureAttributeDescriptor) this.getValue()).getName();
84
        }
85
        
86
    }
87

    
88
    private class ColumnController implements DocumentListener, ChangeListener, ActionListener {
89

    
90
        private final JTextComponent txtName;
91
        private final JComboBox cboDataType;
92
        private final JButton btnDataType;
93
        private final JButton btnExpressionBookmarks;
94
        private final JButton btnExpressionHistory;
95
        private final JButton btnExpression;
96
        private final JTextComponent txtExpression;
97
        private ExpressionPickerController expPicker;
98
        private DataTypePickerController pickerDataType;
99
        private boolean hasChanges;
100
        private final JTextComponent txtSize;
101
        private final JTextComponent txtPrecision;
102
        private final JTextComponent txtScale;
103
        
104
        private final Logger LOGGER = LoggerFactory.getLogger(ColumnController.class);
105
        private final JButton btnColumnMore;
106
        private final JButton btnApplyChanges;
107

    
108
        public ColumnController(
109
                JTextComponent txtName,
110
                JComboBox cboDataType,
111
                JButton btnDataType,
112
                JTextComponent txtExpression,
113
                JButton btnExpression,
114
                JButton btnExpressionHistory,
115
                JButton btnExpressionBookmarks,
116
                JTextComponent txtSize,
117
                JTextComponent txtPrecision,
118
                JTextComponent txtScale,
119
                JButton btnApplyChanges,
120
                JButton btnColumnMore
121
        ) {
122
            this.txtName = txtName;
123
            this.cboDataType = cboDataType;
124
            this.btnDataType = btnDataType;
125
            this.txtExpression = txtExpression;
126
            this.btnExpression = btnExpression;
127
            this.btnExpressionHistory = btnExpressionHistory;
128
            this.btnExpressionBookmarks = btnExpressionBookmarks;
129
            this.txtSize = txtSize;
130
            this.txtPrecision = txtPrecision;
131
            this.txtScale = txtScale;
132
            this.btnApplyChanges = btnApplyChanges;
133
            this.btnColumnMore = btnColumnMore;
134
            this.hasChanges = false;
135
            this.initComponents();
136
            this.setEnabled(false);
137
        }
138

    
139
        public void initComponents() {
140
            this.pickerDataType = ToolsSwingLocator.getToolsSwingManager().createDataTypePickerController(this.cboDataType, this.btnDataType, false);
141

    
142
            ExpressionEvaluatorSwingManager managerExpSwing = ExpressionEvaluatorSwingLocator.getManager();
143
            this.expPicker = managerExpSwing.createExpressionPickerController(
144
                    txtExpression,
145
                    btnExpression,
146
                    btnExpressionBookmarks,
147
                    btnExpressionHistory
148
            );
149
            
150

    
151
            this.txtName.getDocument().addDocumentListener(this);
152
            this.cboDataType.addActionListener(this);
153
            this.txtExpression.getDocument().addDocumentListener(this);
154
            this.txtSize.getDocument().addDocumentListener(this);
155
            this.txtPrecision.getDocument().addDocumentListener(this);
156
            this.txtScale.getDocument().addDocumentListener(this);
157
            //Todo: que el listener expresion lo gestion el picker
158
            
159
            this.cboDataType.addActionListener(new ActionListener() {
160
                @Override
161
                public void actionPerformed(ActionEvent ae) {
162
                    doSetDefaultValuesForDataType();
163
                    doEnabledByDataType();
164
                }
165
            });
166

    
167
        }
168
        
169
        public void doEnabledByDataType() {
170
            JComboBox comboBox = cboDataType;
171
            if (comboBox.getSelectedItem()==null) {
172
                return;
173
            }
174
            DataType dataType = (DataType) comboBox.getSelectedItem();
175
            txtSize.setEnabled(dataType.supportSize());
176
            txtPrecision.setEnabled(dataType.supportPrecision());
177
            txtScale.setEnabled(dataType.supportScale());
178
        }
179
        
180
        public void doSetDefaultValuesForDataType() {
181
            if (this.cboDataType.getSelectedItem()==null) {
182
                return;
183
            }
184
            DataType dataType = (DataType) this.cboDataType.getSelectedItem();
185
            if (dataType.supportSize() && txtSize.getText().isEmpty()) {
186
                txtSize.setText(String.valueOf(dataType.getDefaultSize()));
187
            } else if (!dataType.supportSize()) {
188
                txtSize.setText("");
189
            }
190

    
191
            if (dataType.supportPrecision() && txtPrecision.getText().isEmpty()) {
192
                txtPrecision.setText(String.valueOf(dataType.getDefaultPrecision()));
193
            } else if (!dataType.supportPrecision()) {
194
                txtPrecision.setText("");
195
            }
196

    
197
            if (dataType.supportScale() && txtScale.getText().isEmpty()) {
198
                txtScale.setText(String.valueOf(dataType.getDefaultScale()));
199
            } else if (!dataType.supportScale()) {
200
                txtScale.setText("");
201
            }
202
        }
203

    
204
        public boolean hasChanges() {
205
            return this.hasChanges;
206
        }
207

    
208
        public void setEnabled(boolean enabled) {
209
            this.txtName.setEnabled(enabled);
210
            this.expPicker.setEnabled(enabled);
211
            this.cboDataType.setEnabled(enabled);
212
            this.txtSize.setEnabled(enabled);
213
            this.txtPrecision.setEnabled(enabled);
214
            this.txtScale.setEnabled(enabled);
215
            this.btnApplyChanges.setEnabled(enabled);
216
            this.btnColumnMore.setEnabled(enabled);
217
        }
218

    
219
        public void clean() {
220
            this.txtName.setText("");
221
            this.expPicker.set(null);
222
            this.cboDataType.setSelectedIndex(0);
223
            this.txtSize.setText("");
224
            this.txtPrecision.setText("");
225
            this.txtScale.setText("");
226
            this.btnApplyChanges.setEnabled(false);
227
            this.btnColumnMore.setEnabled(false);
228
            this.hasChanges = false;
229

    
230
        }
231

    
232
        public void put(EditableFeatureAttributeDescriptor attr) {
233
            this.clean();
234
            this.txtName.setText(attr.getName());
235
            FeatureAttributeEmulatorExpression emu = (FeatureAttributeEmulatorExpression) attr.getFeatureAttributeEmulator();
236
            if (emu != null) {
237
                try {
238
                    this.expPicker.set(emu.getExpression().clone());
239
                } catch (CloneNotSupportedException ex) {
240
                    LOGGER.warn("Not able to clone expression.", ex);
241
                    throw new RuntimeException(ex);
242
                }
243
            }
244
            this.pickerDataType.set(attr.getDataType());
245
            Coercion coerceString = ToolsLocator.getDataTypesManager().get(DataTypes.STRING).getCoercion();
246
            txtSize.setEnabled(attr.getDataType().supportSize());
247
            if (attr.getDataType().supportSize()) {
248
                try {
249
                    this.txtSize.setText((String) coerceString.coerce(attr.getSize()));
250
                } catch (CoercionException ex) {
251
                    LOGGER.warn("Not able to coerce text to integer from size box.", ex);
252
                }
253
            }
254
            txtPrecision.setEnabled(attr.getDataType().supportPrecision());
255
            if (attr.getDataType().supportPrecision()) {
256
                try {
257
                    this.txtPrecision.setText((String) coerceString.coerce(attr.getPrecision()));
258
                } catch (CoercionException ex) {
259
                    LOGGER.warn("Not able to coerce text to integer from precision box.", ex);
260
                }
261
            }
262
            txtScale.setEnabled(attr.getDataType().supportScale());
263
            if (attr.getDataType().supportScale()) {
264
                try {
265
                    this.txtScale.setText((String) coerceString.coerce(attr.getScale()));
266
                } catch (CoercionException ex) {
267
                    LOGGER.warn("Not able to coerce text to integer from scale box.", ex);
268
                }
269
            }
270
//            doEnabledByDataType();
271
            this.btnColumnMore.setEnabled(true);
272
            this.btnApplyChanges.setEnabled(false);
273
            this.hasChanges = false;
274
        }
275

    
276
        public EditableFeatureAttributeDescriptor fetch(EditableFeatureAttributeDescriptor attr) {
277
            attr.setName(this.txtName.getText());
278
            try {
279
                Expression exp = this.expPicker.get();
280
                if (exp!=null) {
281
                    attr.setFeatureAttributeEmulator(exp.clone());
282
                } else {
283
                    attr.setFeatureAttributeEmulator((Expression) null);
284
                }
285
            } catch (CloneNotSupportedException ex) {
286
                LOGGER.warn("Not able to clone expression.", ex);
287
                throw new RuntimeException(ex);
288
            }
289
            attr.setDataType(this.pickerDataType.get());
290
            Coercion coerceInteger = ToolsLocator.getDataTypesManager().get(DataTypes.INTEGER).getCoercion();
291
            try {
292
                if (attr.getDataType().supportSize()) {
293
                    attr.setSize((int) coerceInteger.coerce(this.txtSize.getText()));
294
                }
295
            } catch (CoercionException ex) {
296
                LOGGER.warn("Not able to coerce text to integer from size box.", ex);
297
            }
298
            try {
299
                if (attr.getDataType().supportPrecision()) {
300
                    attr.setPrecision((int) coerceInteger.coerce(this.txtPrecision.getText()));
301
                }
302
            } catch (CoercionException ex) {
303
                LOGGER.warn("Not able to coerce text to integer from precision box.", ex);
304
            }
305
            try {
306
                if (attr.getDataType().supportScale()) {
307
                    attr.setScale((int) coerceInteger.coerce(this.txtScale.getText()));
308
                }
309
            } catch (CoercionException ex) {
310
                LOGGER.warn("Not able to coerce text to integer from scale box.", ex);
311
            }
312
            this.hasChanges = false;
313
            this.btnColumnMore.setEnabled(true);
314
            this.btnApplyChanges.setEnabled(false);
315
            return attr;
316
        }
317

    
318
        private void doHasChanges() {
319
            this.btnColumnMore.setEnabled(false);
320
            this.btnApplyChanges.setEnabled(true);
321
            this.hasChanges = true;
322
        }
323

    
324
        @Override
325
        public void insertUpdate(DocumentEvent de) {
326
            doHasChanges();
327
        }
328

    
329
        @Override
330
        public void removeUpdate(DocumentEvent de) {
331
            doHasChanges();
332
        }
333

    
334
        @Override
335
        public void changedUpdate(DocumentEvent de) {
336
            doHasChanges();
337
        }
338

    
339
        @Override
340
        public void stateChanged(ChangeEvent ce) {
341
            doHasChanges();
342
        }
343

    
344
        @Override
345
        public void actionPerformed(ActionEvent ae) {
346
            doHasChanges();
347
        }
348
        
349
        public void setStore(FeatureStore store) {
350
          DALSwingLocator.getManager().configureExpressionBuilder(expPicker.getConfig(), store);
351
//             FeatureStoreElement calculatedStoreElement = DALSwingLocator.getSwingManager()
352
//                    .createFeatureStoreElement();
353
//            calculatedStoreElement.setFeatureStore(store);
354
//            this.expPicker.removeAllSymbolTables();
355
//            this.expPicker.addElement(calculatedStoreElement);
356
        }
357
    }
358

    
359
    private ColumnController columnController;
360
    private FeatureStore store;
361
    private FeatureType featureType;
362
    private FeatureQuery query;
363
//    private JExpressionBuilder pckExpression;
364
    private static final String COLUMN_DEFAULT_NAME = "Field";
365
    private EditableFeatureAttributeDescriptor actualEditableAttribute;
366
    private DefaultListModel lstAttributesModel;
367
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultFeatureQueryCalculatedColumnsPanel.class);
368

    
369
    public DefaultFeatureQueryCalculatedColumnsPanel() {
370
        this.columnController = null;
371
        this.initComponents();
372
    }
373

    
374
    @Override
375
    public JComponent asJComponent() {
376
        return this;
377
    }
378

    
379
    @Override
380
    public ImageIcon loadImage(String imageName) {
381
        return ToolsSwingUtils.loadImage(this, imageName);
382
    }
383

    
384
    @Override
385
    public void setStore(FeatureStore store) {
386
        try {
387
            this.featureType = store.getDefaultFeatureType();
388
            this.store = store;
389
            this.query = store.createFeatureQuery();
390
            this.columnController.setStore(store);
391
//            this.pckExpression = DALSwingLocator.getManager().createQueryFilterExpresion(store);
392
        } catch (DataException ex) {
393
            throw new RuntimeException("Can't assign store", ex);
394
        }
395
    }
396

    
397
    private void initComponents() {
398
        ToolsSwingManager toolsSwingManager = ToolsSwingLocator.getToolsSwingManager();
399

    
400
        IconTheme theme = ToolsSwingLocator.getIconThemeManager().getCurrent();
401
        ImageIcon icon = theme.get("picker-datatype");
402
        this.btnColumnDataType.setIcon(icon);
403
        toolsSwingManager.translate(this.lblExpression);
404
        toolsSwingManager.translate(this.lblName);
405
        toolsSwingManager.translate(this.lblType);
406
        toolsSwingManager.translate(this.lblSize);
407
        toolsSwingManager.translate(this.lblPrecision);
408
        toolsSwingManager.translate(this.lblScale);
409
        toolsSwingManager.translate(this.btnApplyChanges);
410
        toolsSwingManager.translate(this.btnColumnMore);
411

    
412
        this.columnController = new ColumnController(
413
                this.txtColumnName,
414
                this.cboColumnDataType,
415
                this.btnColumnDataType,
416
                this.txtColumnExpression,
417
                this.btnColumnExpression,
418
                this.btnColumnExpressionHistory,
419
                this.btnColumnExpressionBookmarks,
420
                this.txtColumnSize,
421
                this.txtColumnPrecision,
422
                this.txtColumnScale,
423
                this.btnApplyChanges,
424
                this.btnColumnMore
425
        );
426
//        this.lstAttributes.setCellRenderer(new FeatureAttributeListCellRenderer());
427

    
428
        this.lstAttributes.addListSelectionListener((ListSelectionEvent e) -> {
429
            if (e.getValueIsAdjusting()) {
430
                return;
431
            }
432
            doSelectAttribute();
433
        });
434

    
435
        Dimension sz = this.getPreferredSize();
436
        if (sz.width < DEFAULT_WIDTH) {
437
            sz.width = DEFAULT_WIDTH;
438
        }
439
        if (sz.height < DEFAULT_HEIGHT) {
440
            sz.height = DEFAULT_HEIGHT;
441
        }
442
        this.setPreferredSize(sz);
443

    
444
        this.lstAttributesModel = new DefaultListModel<ListElement<EditableFeatureAttributeDescriptor>>();
445
//        this.lstAttributesModel = ToolsSwingLocator.getToolsSwingManager().createFilteredListModel();
446
        this.lstAttributes.setModel(lstAttributesModel);
447

    
448
        this.lstAttributes.setSelectionModel(new DefaultListSelectionModel() {
449

    
450
            @Override
451
            public void setSelectionInterval(int index0, int index1) {
452
                if (checkColumnControllerHasChangesWithUser()) {
453
                    super.setSelectionInterval(index0, index1);
454
                    doSelectAttribute();
455
                }
456
            }
457

    
458
        });
459

    
460
        this.btnAdd.addActionListener((ActionEvent e) -> {
461
            if (checkColumnControllerHasChangesWithUser()) {
462
                doAdd();
463
            }
464
        });
465

    
466
        this.btnRemove.addActionListener((ActionEvent e) -> {
467
            doRemove();
468
        });
469

    
470
        this.btnUp.addActionListener((ActionEvent e) -> {
471
            doUp(lstAttributes);
472
        });
473

    
474
        this.btnDown.addActionListener((ActionEvent e) -> {
475
            doDown(lstAttributes);
476
        });
477

    
478
        this.btnApplyChanges.addActionListener((ActionEvent e) -> {
479
            doApplyChanges();
480
        });
481

    
482
        this.btnColumnMore.addActionListener((ActionEvent e) -> {
483
            doColumnMore();
484
        });
485
        
486
    }
487

    
488
    private boolean checkColumnControllerHasChangesWithUser() {
489
        if (this.hasChanges()) {
490
            I18nManager i18n = ToolsLocator.getI18nManager();
491
            String message = i18n.getTranslation("_Changes_has_not_been_saved_Are_you_sure_you_want_to_continue");
492
            String title = i18n.getTranslation("_Changes_not_saved");
493
            int r = ToolsSwingLocator.getThreadSafeDialogsManager().confirmDialog(message, title,
494
                    JOptionPane.YES_NO_OPTION,
495
                    JOptionPane.QUESTION_MESSAGE);
496
            if (r == JOptionPane.NO_OPTION) {
497
                return false;
498
            }
499

    
500
        }
501
        return true;
502
    }
503

    
504
    private void doColumnMore() {
505
        if (this.columnController == null) {
506
            return;
507
        }
508
        final I18nManager i18n = ToolsLocator.getI18nManager();
509
        WindowManager_v2 winManager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
510
        final FeatureTypeAttributePanel panel = DALSwingLocator.getSwingManager().createFeatureTypeAttributePanel();
511
        panel.clean();
512
//                panel.setNameAsNew(featureType);
513
        panel.put(actualEditableAttribute);
514
        panel.setMode(FeatureTypeAttributePanel.MODE_VIRTUAL_FIELD);
515
        final Dialog dialog = winManager.createDialog(
516
                panel.asJComponent(),
517
                i18n.getTranslation("_Extra_column"),
518
                null,
519
                WindowManager_v2.BUTTONS_OK_CANCEL
520
        );
521
        dialog.addActionListener(new ActionListener() {
522
            @Override
523
            public void actionPerformed(ActionEvent e) {
524
                if (dialog.getAction() != WindowManager_v2.BUTTONS_OK) {
525
                    return;
526
                }
527
                try {
528
                    FeatureAttributeDescriptor prev = actualEditableAttribute.getCopy();
529
                    panel.fetch(actualEditableAttribute);
530
                    columnController.put(actualEditableAttribute);
531
                    if (!prev.equals(actualEditableAttribute)) {
532
                        columnController.doHasChanges();
533
                    }
534
                } catch (Exception ex) {
535
                    LOGGER.warn("Problems updating feature descriptor.", ex);
536
                }
537
            }
538
        });
539
        dialog.show(WindowManager.MODE.DIALOG);
540
    }
541

    
542
    public boolean checkPanel(StringBuilder msg) {
543
        I18nManager i18n = ToolsLocator.getI18nManager();
544
        if (this.hasChanges()) {
545
            int r = ToolsSwingLocator.getThreadSafeDialogsManager().confirmDialog(
546
                    i18n.getTranslation("_Changes_has_not_been_saved_Are_you_sure_you_want_to_continue"),
547
                    i18n.getTranslation("_Changes_not_saved"),
548
                    JOptionPane.YES_NO_OPTION,
549
                    JOptionPane.QUESTION_MESSAGE);
550
            if (r == JOptionPane.NO_OPTION) {
551
                return false;
552
            }
553
        }
554
        return true;
555
    }
556

    
557
    public boolean hasChanges() {
558
        return this.columnController.hasChanges();
559
    }
560

    
561
    private void doSelectAttribute() {
562
        int index = this.lstAttributes.getSelectedIndex();
563

    
564
        ListModel model = this.lstAttributesModel;
565
        this.btnUp.setEnabled(index >= 1);
566
        this.btnDown.setEnabled(index >= 0 && index < this.lstAttributesModel.getSize() - 1);
567
        
568
        EditableFeatureAttributeDescriptor value = null;
569
        if (this.lstAttributes.getSelectedValue() != null) {
570
            ListElement<EditableFeatureAttributeDescriptor> selectedValue = (ListElement<EditableFeatureAttributeDescriptor>) this.lstAttributes.getSelectedValue();
571
            if (selectedValue != null) {
572
                value = selectedValue.getValue();
573
            }
574
        }
575
        if (value == null) {
576
            this.columnController.clean();
577
            this.columnController.setEnabled(false);
578
            this.actualEditableAttribute = null;
579

    
580
        } else {
581
            //EditableFeatureAttributeDescriptor value = node.getValue();
582
            this.actualEditableAttribute = value;
583
            columnController.setEnabled(true);
584
            columnController.put(value);
585
        }
586
    }
587

    
588
    @Override
589
    public FeatureQuery fetch(FeatureQuery query) {
590
        if (hasChanges()) {
591
            I18nManager i18n = ToolsLocator.getI18nManager();
592
            String message = i18n.getTranslation("_Changes_has_not_been_saved_Do_you_want_to_save_them_before_continue");
593
            String title = i18n.getTranslation("_Changes_not_saved");
594
            int r = ToolsSwingLocator.getThreadSafeDialogsManager().confirmDialog(message, title,
595
                    JOptionPane.YES_NO_OPTION,
596
                    JOptionPane.QUESTION_MESSAGE);
597
            if (r == JOptionPane.YES_NO_OPTION) {
598
                doApplyChanges();
599
            }
600
        }
601
        
602
        if (query == null) {
603
            return this.query.getCopy();
604
        }
605

    
606
        this.query.getExtraColumn().clear();
607
        for (int i = 0; i < lstAttributesModel.getSize(); i++) {
608
            ListElement<EditableFeatureAttributeDescriptor> element = (ListElement<EditableFeatureAttributeDescriptor>) lstAttributesModel.get(i);
609
            EditableFeatureAttributeDescriptor newExtraColumn = this.query.getExtraColumn().add(element.getValue().getName(), element.getValue().getType());
610
            newExtraColumn.copyFrom(element.getValue());
611
        }
612
        query.copyFrom(this.query);
613

    
614
        return query;
615
    }
616

    
617
    @Override
618
    public FeatureQuery fetch() {
619
        return this.fetch(null);
620
    }
621

    
622
    @Override
623
    public void put(FeatureQuery query) {
624
        this.query.copyFrom(query);
625
        addExtraColumns(this.query);
626
    }
627

    
628
    private void addExtraColumns(FeatureQuery query) {
629
        List<EditableFeatureAttributeDescriptor> cols = query.getExtraColumn().getColumns();
630
        if (cols == null || cols.isEmpty()) {
631
            return;
632
        }
633
        for (EditableFeatureAttributeDescriptor col : cols) {
634
            ListElement lf = new AttributeListElement(col);
635
            this.lstAttributesModel.addElement(lf);
636
        }
637
        if (this.lstAttributesModel.getSize() > 0) {
638
            this.lstAttributes.setSelectedIndex(0);
639
        }
640
    }
641

    
642
    public static void selfRegister() {
643
        boolean n = ToolsSwingUtils.registerIcons( 
644
                DefaultFeatureQueryOrderPanel.class,
645
                null,
646
                LIBRARY_NAME,
647
                new String[]{ "featurequery", "featurequery-column-add"},
648
                new String[]{ "featurequery", "featurequery-column-remove"},
649
                new String[]{ "featurequery", "featurequery-column-down"},
650
                new String[]{ "featurequery", "featurequery-column-up"}
651
        );          
652
    }
653

    
654
    private void doAdd() {
655
        int id = 0;
656
        String newName = COLUMN_DEFAULT_NAME;
657
        while (checkIfValueExistInModel(newName, this.lstAttributesModel)) {
658
            newName = COLUMN_DEFAULT_NAME + "_" + id;
659
            id += 1;
660
        }
661
        EditableFeatureAttributeDescriptor newAttr = DALLocator.getDataManager().createFeatureAttributeDescriptor(
662
                newName,
663
                DataTypes.STRING
664
        );
665
        if (newAttr.getDataType().supportSize()) {
666
            newAttr.setSize(newAttr.getDataType().getDefaultSize());
667
        }
668
        this.columnController.put(newAttr);
669
        this.columnController.setEnabled(true);
670

    
671
        this.lstAttributesModel.addElement(new AttributeListElement(newAttr));
672
        ListElement.setSelected(this.lstAttributes, newAttr);
673
        this.lstAttributes.revalidate();
674
        this.lstAttributes.repaint();
675
        this.actualEditableAttribute = newAttr;
676

    
677
    }
678

    
679
    private boolean checkIfValueExistInModel(String name, ListModel<ListElement<EditableFeatureAttributeDescriptor>> model) {
680
        for (int i = 0; i < model.getSize(); i++) {
681
            EditableFeatureAttributeDescriptor element = model.getElementAt(i).getValue();
682
            if (StringUtils.equals(element.getLabel(), name)) {
683
                return true;
684
            }
685

    
686
        }
687
        return false;
688
    }
689

    
690
    private void doRemove() {
691
        AttributeListElement selectedValue = (AttributeListElement) this.lstAttributes.getSelectedValue();
692
        if( selectedValue == null ) {
693
            return;
694
        }
695
        FeatureAttributeDescriptor attr = selectedValue.getValue();
696
        if( attr == null ) {
697
            return;
698
        }
699
        boolean removeFromAggregateFunctions = false;
700
        boolean removeFromOrder = false;
701
        boolean removeFromGroupByColums = false;
702
        if( this.query.getAggregateFunctions().containsKey(attr.getName()) ) {
703
            ThreadSafeDialogsManager dialogs = ToolsSwingLocator.getThreadSafeDialogsManager();
704
            int n = dialogs.confirmDialog(
705
                    "El campo '"+attr.getName()+"' se esta usando en una funcion de agregado. ? Dese borrarlo igualmente ?", 
706
                    "Eliminar campo", 
707
                    JOptionPane.YES_NO_OPTION, 
708
                    JOptionPane.QUESTION_MESSAGE, 
709
                    "_FeatureQueryCalculatedColumns_remove_used_column"
710
            );
711
            if( n != JOptionPane.YES_OPTION ) {
712
                return;
713
            }
714
            n = dialogs.confirmDialog(
715
                    "? Desea eliminar la funcion de agregado donde se esta usando el campo '"+attr.getName()+"' ?", 
716
                    "Eliminar campo", 
717
                    JOptionPane.YES_NO_OPTION, 
718
                    JOptionPane.QUESTION_MESSAGE, 
719
                    "_FeatureQueryCalculatedColumns_remove_aggregate_function_when_remove_column"
720
            );
721
            if( n == JOptionPane.YES_OPTION ) {
722
                removeFromAggregateFunctions = true;
723
            } else {
724
                LOGGER.info("It has been decided not to delete the aggregate function of a deleted field");
725
            }
726
        }
727
        if( this.query.getGroupByColumns().contains(attr.getName()) ) {
728
            ThreadSafeDialogsManager dialogs = ToolsSwingLocator.getThreadSafeDialogsManager();
729
            int n = dialogs.confirmDialog(
730
                    "El campo '"+attr.getName()+"' se esta usando como campo de agrupacion. ? Dese borrarlo igualmente ?", 
731
                    "Eliminar campo", 
732
                    JOptionPane.YES_NO_OPTION, 
733
                    JOptionPane.QUESTION_MESSAGE, 
734
                    "_FeatureQueryCalculatedColumns_remove_used_column"
735
            );
736
            if( n != JOptionPane.YES_OPTION ) {
737
                return;
738
            }
739
            n = dialogs.confirmDialog(
740
                    "? Desea eliminar la agrupacion por el campo '"+attr.getName()+"' ?", 
741
                    "Eliminar campo", 
742
                    JOptionPane.YES_NO_OPTION, 
743
                    JOptionPane.QUESTION_MESSAGE, 
744
                    "_FeatureQueryCalculatedColumns_remove_group_by_column_when_remove_column"
745
            );
746
            if( n == JOptionPane.YES_OPTION ) {
747
                removeFromGroupByColums = true;
748
            } else {
749
                LOGGER.info("It has been decided not to delete the group by a deleted field");
750
            }
751
        }
752
        if( this.query.getOrder().contains(attr.getName()) ) {
753
            ThreadSafeDialogsManager dialogs = ToolsSwingLocator.getThreadSafeDialogsManager();
754
            int n = dialogs.confirmDialog(
755
                    "El campo '"+attr.getName()+"' se esta usando para establecer el orden. ? Dese borrarlo igualmente ?", 
756
                    "Eliminar campo", 
757
                    JOptionPane.YES_NO_OPTION, 
758
                    JOptionPane.QUESTION_MESSAGE, 
759
                    "_FeatureQueryCalculatedColumns_remove_used_column"
760
            );
761
            if( n != JOptionPane.YES_OPTION ) {
762
                return;
763
            }
764

    
765
            n = dialogs.confirmDialog(
766
                    "? Desea eliminar el uso del campo '"+attr.getName()+"' en la ordenacion ?", 
767
                    "Eliminar campo", 
768
                    JOptionPane.YES_NO_OPTION, 
769
                    JOptionPane.QUESTION_MESSAGE, 
770
                    "_FeatureQueryCalculatedColumns_remove_order_when_remove_column"
771
            );
772
            if( n == JOptionPane.YES_OPTION ) {
773
                removeFromOrder = true;
774
            } else {
775
                LOGGER.info("It has been decided not to delete the order by a deleted field");
776
            }
777
        }
778
        if( removeFromAggregateFunctions ) {
779
           this.query.removeAggregateFunction(attr.getName());
780
        }
781
        if( removeFromOrder ) {
782
            int index = this.query.getOrder().getIndex(attr.getName());
783
            this.query.getOrder().remove(index);
784
        }
785
        if( removeFromGroupByColums ) {
786
            this.query.removeGroupByColumn(attr.getName());
787
        }
788
        
789
        ListSelectionModel lsm = lstAttributes.getSelectionModel();
790
        DefaultListModel model = (DefaultListModel) this.lstAttributes.getModel();
791
        int actualIndex = lsm.getMinSelectionIndex();
792
        this.lstAttributesModel.removeElement(selectedValue);
793
        this.columnController.clean();
794

    
795
        int size = model.size();
796
        if (size == 0) {
797
            //List is empty: disable delete, up, and down buttons.
798
        } else {
799
            //Adjust the selection.
800
            if (model.getSize() == 0) {
801

    
802
            } else if (actualIndex >= model.getSize()) {
803
                lstAttributes.setSelectedIndex(model.getSize() - 1);
804
            } else {
805
                lstAttributes.setSelectedIndex(actualIndex);
806
            }
807
        }
808
    }
809

    
810
    private void doApplyChanges() {
811
        this.columnController.fetch(this.actualEditableAttribute);
812
        this.lstAttributes.invalidate();
813
        this.lstAttributes.repaint();
814
    }
815

    
816
    private void doUp(JList lstColumns) {
817
        int moveMe = lstColumns.getSelectedIndex();
818
        if (moveMe != 0) {
819
            //not already at top
820
            swap(lstColumns, moveMe, moveMe - 1);
821
            lstColumns.setSelectedIndex(moveMe - 1);
822
            lstColumns.ensureIndexIsVisible(moveMe - 1);
823
        }
824
    }
825

    
826
    private void doDown(JList lstColumns) {
827
        int moveMe = lstColumns.getSelectedIndex();
828
        if (moveMe != lstColumns.getModel().getSize() - 1) {
829
            //not already at bottom
830
            swap(lstColumns, moveMe, moveMe + 1);
831
            lstColumns.setSelectedIndex(moveMe + 1);
832
            lstColumns.ensureIndexIsVisible(moveMe + 1);
833
        }
834
    }
835

    
836
    private void swap(JList lstColumns, int a, int b) {
837
        DefaultListModel model = (DefaultListModel) lstColumns.getModel();
838
        Object aObject = model.getElementAt(a);
839
        Object bObject = model.getElementAt(b);
840
        model.set(a, bObject);
841
        model.set(b, aObject);
842
    }
843
}