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 / searchpanel / DefaultSearchPanel.java @ 46062

History | View | Annotate | Download (73.8 KB)

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

    
3
import java.awt.BorderLayout;
4
import java.awt.Cursor;
5
import java.awt.FlowLayout;
6
import java.awt.event.ActionEvent;
7
import java.awt.event.ActionListener;
8
import java.awt.event.ComponentAdapter;
9
import java.awt.event.ComponentEvent;
10
import java.awt.event.KeyAdapter;
11
import java.awt.event.KeyEvent;
12
import java.net.URL;
13
import java.text.DateFormat;
14
import java.text.SimpleDateFormat;
15
import java.util.ArrayList;
16
import java.util.Calendar;
17
import java.util.Collection;
18
import java.util.Collections;
19
import java.util.Date;
20
import java.util.HashMap;
21
import java.util.List;
22
import java.util.Map;
23
import java.util.Objects;
24
import javax.swing.AbstractAction;
25
import javax.swing.Action;
26
import static javax.swing.Action.ACTION_COMMAND_KEY;
27
import static javax.swing.Action.NAME;
28
import javax.swing.BorderFactory;
29
import javax.swing.ImageIcon;
30
import javax.swing.JButton;
31
import javax.swing.JComponent;
32
import javax.swing.JMenuItem;
33
import javax.swing.JOptionPane;
34
import javax.swing.JPopupMenu;
35
import javax.swing.JTable;
36
import javax.swing.ListSelectionModel;
37
import javax.swing.SwingUtilities;
38
import javax.swing.event.ChangeEvent;
39
import javax.swing.event.ListSelectionEvent;
40
import javax.swing.event.ListSelectionListener;
41
import javax.swing.table.DefaultTableModel;
42
import javax.swing.table.TableCellRenderer;
43
import javax.swing.table.TableModel;
44
import org.apache.commons.io.FilenameUtils;
45
import org.apache.commons.lang.mutable.MutableObject;
46
import org.apache.commons.lang3.StringUtils;
47
import org.apache.commons.lang3.mutable.MutableLong;
48
import org.gvsig.configurableactions.ConfigurableActionsMamager;
49
import org.gvsig.expressionevaluator.Expression;
50
import org.gvsig.expressionevaluator.ExpressionBuilder;
51
import org.gvsig.expressionevaluator.ExpressionUtils;
52
import static org.gvsig.fmap.dal.DataManager.DAL_USE_LABELS;
53
import static org.gvsig.fmap.dal.DataManager.USE_LABELS_BOTH;
54
import static org.gvsig.fmap.dal.DataManager.USE_LABELS_NO;
55
import static org.gvsig.fmap.dal.DataManager.USE_LABELS_YES;
56
import org.gvsig.fmap.dal.DataStore;
57
import org.gvsig.fmap.dal.DataStoreProviderFactory;
58
import org.gvsig.fmap.dal.complements.Search;
59
import org.gvsig.fmap.dal.exception.DataException;
60
import org.gvsig.fmap.dal.feature.Feature;
61
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
62
import org.gvsig.fmap.dal.feature.FeatureQuery;
63
import org.gvsig.fmap.dal.feature.FeatureStore;
64
import org.gvsig.fmap.dal.feature.FeatureStoreProviderFactory;
65
import org.gvsig.fmap.dal.feature.FeatureType;
66
import org.gvsig.fmap.dal.feature.paging.FacadeOfAFeaturePagingHelper;
67
import org.gvsig.fmap.dal.swing.AbstractDALActionFactory.AbstractDALActionContext;
68
import org.gvsig.fmap.dal.swing.DALActionFactory;
69
import org.gvsig.fmap.dal.swing.DALSwingLocator;
70
import org.gvsig.fmap.dal.swing.DataSwingManager;
71
import org.gvsig.fmap.dal.swing.featurequery.FeatureQueryCalculatedColumnsPanel;
72
import org.gvsig.fmap.dal.swing.impl.featurequery.DefaultFeatureQueryGroupByPanel;
73
import org.gvsig.fmap.dal.swing.searchpanel.FeatureStoreSearchPanel;
74
import org.gvsig.fmap.dal.swing.searchpanel.SearchConditionPanel;
75
import org.gvsig.fmap.dal.swing.searchpanel.SearchConditionPanel.SearchConditionPanelFactory;
76
import org.gvsig.tools.ToolsLocator;
77
import org.gvsig.tools.dataTypes.DataType;
78
import org.gvsig.tools.dynobject.Tags;
79
import org.gvsig.tools.i18n.I18nManager;
80
import org.gvsig.tools.swing.api.ActionListenerSupport;
81
import org.gvsig.tools.swing.api.ToolsSwingLocator;
82
import org.gvsig.tools.swing.api.ToolsSwingManager;
83
import org.gvsig.tools.swing.api.windowmanager.Dialog;
84
import org.gvsig.tools.swing.api.windowmanager.WindowManager;
85
import org.gvsig.tools.swing.api.windowmanager.WindowManager_v2;
86
import org.gvsig.tools.swing.icontheme.IconTheme;
87
import org.gvsig.tools.util.ToolsUtilLocator;
88
import org.slf4j.Logger;
89
import org.slf4j.LoggerFactory;
90
import org.gvsig.fmap.dal.swing.featurequery.FeatureQueryGroupByPanel;
91
import org.gvsig.fmap.dal.swing.featurequery.FeatureQueryOrderPanel;
92
import org.gvsig.fmap.dal.swing.featuretable.SimpleFeaturesTableModel;
93
import org.gvsig.fmap.dal.swing.impl.featurequery.DefaultFeatureQueryCalculatedColumnsPanel;
94
import org.gvsig.fmap.dal.swing.featuretype.FeatureAttributesSelectionPanel;
95
import org.gvsig.fmap.dal.swing.impl.featuretable.SimpleFeaturesTableModelImpl;
96
import org.gvsig.fmap.dal.swing.searchPostProcess.SearchPostProcess;
97
import org.gvsig.fmap.dal.swing.searchPostProcess.SearchPostProcessFactory;
98
import org.gvsig.fmap.dal.swing.searchpanel.SearchParameters;
99
import org.gvsig.tools.bookmarksandhistory.Bookmark;
100
import org.gvsig.tools.bookmarksandhistory.Bookmarks;
101
import org.gvsig.tools.bookmarksandhistory.History;
102
import org.gvsig.tools.dispose.Disposable;
103
import org.gvsig.tools.dispose.DisposeUtils;
104
import org.gvsig.tools.dynform.DynFormLocator;
105
import org.gvsig.tools.dynform.JDynForm;
106
import org.gvsig.tools.dynobject.DynObject;
107
import org.gvsig.tools.swing.api.SupportIsEnable;
108
import org.gvsig.tools.swing.api.SupportIsVisible;
109
import org.gvsig.tools.swing.api.ToolsSwingUtils;
110
import org.gvsig.tools.swing.api.bookmarkshistory.ActionEventWithCurrentValue;
111
import static org.gvsig.tools.swing.api.bookmarkshistory.ActionEventWithCurrentValue.ID_GETVALUE;
112
import static org.gvsig.tools.swing.api.bookmarkshistory.ActionEventWithCurrentValue.ID_SETVALUE;
113
import org.gvsig.tools.swing.api.bookmarkshistory.BookmarksController;
114
import org.gvsig.tools.swing.api.bookmarkshistory.HistoryController;
115
import org.gvsig.tools.swing.api.task.TaskStatusController;
116
import org.gvsig.tools.swing.api.threadsafedialogs.ThreadSafeDialogsManager;
117
import org.gvsig.tools.task.SimpleTaskStatus;
118
import org.gvsig.tools.util.PropertiesSupportHelper;
119

    
120
/**
121
 *
122
 * @author jjdelcerro
123
 */
124
@SuppressWarnings({"UseSpecificCatch"})
125
public class DefaultSearchPanel
126
        extends DefaultSearchPanelView2
127
        implements FeatureStoreSearchPanel, SupportIsEnable, SupportIsVisible {
128

    
129
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultSearchPanel.class);
130

    
131
    static /* friend */ Integer useLabels = null;
132
    private BookmarksController bookmarksController;
133
    private HistoryController historyController;
134
    private FeatureQuery lastQuery;
135
    private Feature lastSelectedFeature;    
136
    private final PropertiesSupportHelper propertiesHelper;
137
    private TaskStatusController taskStatusController;
138

    
139
    public static class UseLabelsYesAction extends AbstractAction {
140

    
141
        @SuppressWarnings("OverridableMethodCallInConstructor")
142
        public UseLabelsYesAction() {
143
            I18nManager i18n = ToolsLocator.getI18nManager();
144

    
145
            this.putValue(NAME, i18n.getTranslation("_Use_labels"));
146
            this.putValue(ACTION_COMMAND_KEY, "UseLabelsYes");
147
        }
148

    
149
        @Override
150
        public Object getValue(String key) {
151
            if (NAME.equals(key)) {
152
                // Cuando se registra la accion aun no se han cargado las traducciones
153
                I18nManager i18n = ToolsLocator.getI18nManager();
154
                return i18n.getTranslation("_Use_labels");
155
            }
156
            return super.getValue(key);
157
        }
158

    
159
        @Override
160
        public void actionPerformed(ActionEvent ae) {
161
            DefaultSearchPanel.useLabels = USE_LABELS_YES;
162
        }
163
    }
164

    
165
    public static class UseLabelsNoAction extends AbstractAction {
166

    
167
        @SuppressWarnings("OverridableMethodCallInConstructor")
168
        public UseLabelsNoAction() {
169
            I18nManager i18n = ToolsLocator.getI18nManager();
170
            this.putValue(NAME, i18n.getTranslation("_Use_names"));
171
            this.putValue(ACTION_COMMAND_KEY, "UseLabelsNo");
172
        }
173

    
174
        @Override
175
        public Object getValue(String key) {
176
            if (NAME.equals(key)) {
177
                // Cuando se registra la accion aun no se han cargado las traducciones
178
                I18nManager i18n = ToolsLocator.getI18nManager();
179
                return i18n.getTranslation("_Use_names");
180
            }
181
            return super.getValue(key);
182
        }
183

    
184
        @Override
185
        public void actionPerformed(ActionEvent ae) {
186
            DefaultSearchPanel.useLabels = USE_LABELS_NO;
187
        }
188
    }
189

    
190
    public static class UseLabelsBothAction extends AbstractAction {
191

    
192
        @SuppressWarnings("OverridableMethodCallInConstructor")
193
        public UseLabelsBothAction() {
194
            I18nManager i18n = ToolsLocator.getI18nManager();
195

    
196
            this.putValue(NAME, i18n.getTranslation("_Use_labels_and_names"));
197
            this.putValue(ACTION_COMMAND_KEY, "UseLabelsBoth");
198
        }
199

    
200
        @Override
201
        public Object getValue(String key) {
202
            if (NAME.equals(key)) {
203
                // Cuando se registra la accion aun no se han cargado las traducciones
204
                I18nManager i18n = ToolsLocator.getI18nManager();
205
                return i18n.getTranslation("_Use_labels_and_names");
206
            }
207
            return super.getValue(key);
208
        }
209

    
210
        @Override
211
        public void actionPerformed(ActionEvent ae) {
212
            DefaultSearchPanel.useLabels = USE_LABELS_BOTH;
213
        }
214
    }
215

    
216
    public static class SelectColumnsAction extends AbstractAction {
217

    
218
        @SuppressWarnings("OverridableMethodCallInConstructor")
219
        public SelectColumnsAction() {
220
            I18nManager i18n = ToolsLocator.getI18nManager();
221

    
222
            this.putValue(NAME, i18n.getTranslation("_Select_columns_to_display"));
223
            this.putValue(ACTION_COMMAND_KEY, "SelectColumns");
224
        }
225

    
226
        @Override
227
        public Object getValue(String key) {
228
            if (NAME.equals(key)) {
229
                // Cuando se registra la accion aun no se han cargado las traducciones
230
                I18nManager i18n = ToolsLocator.getI18nManager();
231
                return i18n.getTranslation("_Select_columns_to_display");
232
            }
233
            return super.getValue(key);
234
        }
235

    
236
        @Override
237
        public void actionPerformed(ActionEvent ae) {
238
            DefaultSearchPanel panel = (DefaultSearchPanel) ae.getSource();
239
            panel.doSelectResultColumnNames();
240
        }
241
    }
242

    
243
    public static class CalculatedColumnsAction extends AbstractAction {
244

    
245
        @SuppressWarnings("OverridableMethodCallInConstructor")
246
        public CalculatedColumnsAction() {
247
            I18nManager i18n = ToolsLocator.getI18nManager();
248

    
249
            this.putValue(NAME, i18n.getTranslation("_Calculated_columns"));
250
            this.putValue(ACTION_COMMAND_KEY, "CalculatedColumns");
251
        }
252

    
253
        @Override
254
        public Object getValue(String key) {
255
            if (NAME.equals(key)) {
256
                // Cuando se registra la accion aun no se han cargado las traducciones
257
                I18nManager i18n = ToolsLocator.getI18nManager();
258
                return i18n.getTranslation("_Calculated_columns");
259
            }
260
            return super.getValue(key);
261
        }
262

    
263
        @Override
264
        public void actionPerformed(ActionEvent ae) {
265
            DefaultSearchPanel panel = (DefaultSearchPanel) ae.getSource();
266
            panel.doCalculatedColumns();
267
        }
268
    }
269

    
270
    public static class GroupByAction extends AbstractAction {
271

    
272
        @SuppressWarnings("OverridableMethodCallInConstructor")
273
        public GroupByAction() {
274
            I18nManager i18n = ToolsLocator.getI18nManager();
275

    
276
            this.putValue(NAME, i18n.getTranslation("_Group_by"));
277
            this.putValue(ACTION_COMMAND_KEY, "GroupBy");
278
        }
279

    
280
        @Override
281
        public Object getValue(String key) {
282
            if (NAME.equals(key)) {
283
                // Cuando se registra la accion aun no se han cargado las traducciones
284
                I18nManager i18n = ToolsLocator.getI18nManager();
285
                return i18n.getTranslation("_Group_by");
286
            }
287
            return super.getValue(key);
288
        }
289

    
290
        @Override
291
        public void actionPerformed(ActionEvent ae) {
292
            DefaultSearchPanel panel = (DefaultSearchPanel) ae.getSource();
293
            panel.doGroupBy();
294
        }
295
    }
296

    
297
    public static class OrderByAction extends AbstractAction {
298

    
299
        @SuppressWarnings("OverridableMethodCallInConstructor")
300
        public OrderByAction() {
301
            I18nManager i18n = ToolsLocator.getI18nManager();
302

    
303
            this.putValue(NAME, i18n.getTranslation("_Order_by"));
304
            this.putValue(ACTION_COMMAND_KEY, "SelectOrderBy");
305
        }
306

    
307
        @Override
308
        public Object getValue(String key) {
309
            if (NAME.equals(key)) {
310
                // Cuando se registra la accion aun no se han cargado las traducciones
311
                I18nManager i18n = ToolsLocator.getI18nManager();
312
                return i18n.getTranslation("_Order_by");
313
            }
314
            return super.getValue(key);
315
        }
316

    
317
        @Override
318
        public void actionPerformed(ActionEvent ae) {
319
            DefaultSearchPanel panel = (DefaultSearchPanel) ae.getSource();
320
            panel.doOrderBy();
321
        }
322
    }
323
    
324
    private class TablePopupMenu extends JPopupMenu {
325
            public final JTable table;
326
            @SuppressWarnings("OverridableMethodCallInConstructor")
327
            public TablePopupMenu(JTable inputTable) {
328
                this.table = inputTable;
329
                I18nManager i18n = ToolsLocator.getI18nManager();
330
                JMenuItem copyRowsActionMenu = new JMenuItem(i18n.getTranslation("_Copy_rows"));
331
                copyRowsActionMenu.addActionListener((ActionEvent e) -> {
332
                    doCopyRows(table);
333
                });
334
                this.add(copyRowsActionMenu);
335
            }
336
        }
337
            
338
    private class ActionButtons {
339

    
340
        private final DALActionFactory factory;
341
        private final Action action;
342
        private final JButton button;
343

    
344
        public ActionButtons(DALActionFactory factory, Action action, JButton button) {
345
            this.factory = factory;
346
            this.action = action;
347
            this.button = button;
348
        }
349
    }
350

    
351
    public static class SearchActionContext extends AbstractDALActionContext {
352

    
353
        private final DefaultSearchPanel panel;
354

    
355
        public SearchActionContext(DefaultSearchPanel panel) {
356
            super(FeatureStoreSearchPanel.ACTION_CONTEXT_NAME);
357
            this.panel = panel;
358
        }
359

    
360
        @Override
361
        public DataStore getStore() {
362
            if (this.panel.currentPostProcess == null || this.panel.tabResults.getSelectedIndex() == 0) {
363
                return this.panel.getStore();
364
            } else {
365
                return this.panel.postProcessStore;
366
//                DataSwingManager manager = DALSwingLocator.getDataSwingManager();
367
//                SearchPostProcessFactory factory= manager.getSearchPostProcess(this.panel.currentPostProcess);
368
//                SearchParameters searchParams = this.panel.parameters.getCopy();
369
//                if (factory.hasProcessParameters()){
370
//                    SearchPostProcess.SearchPostProcessResult searchPostProcessResult = this.panel.doExecuteSearchPostProcess(this.panel.store, this.panel.parameters.getQuery(), factory, this.panel.postProcessParams, searchParams);
371
//                    return searchPostProcessResult.getStore();
372
//                }
373
//                SearchPostProcess.SearchPostProcessResult searchPostProcessResult = this.panel.doExecuteSearchPostProcess(this.panel.store, this.panel.parameters.getQuery(), factory, null, searchParams);
374
//                return searchPostProcessResult.getStore();
375
            }
376
        }
377

    
378
        @Override
379
        public JComponent getActionButton(String actionName) {
380
            return this.panel.getActionButton(actionName);
381
        }
382

    
383
        @Override
384
        public int getSelectedsCount() {
385
            return this.panel.getSelectedFeatureCount();
386
        }
387

    
388
        @Override
389
        public Expression getFilterForSelecteds() {
390
            return this.panel.getFilterForSelectedFeature();
391
        }
392

    
393
        @Override
394
        public FeatureQuery getQuery() {
395
            if (this.panel.currentPostProcess == null || this.panel.tabResults.getSelectedIndex() == 0) {
396
                return this.panel.parameters.getQuery();
397
            } else {
398
                return this.panel.postProcessQuery;
399
//                DataSwingManager manager = DALSwingLocator.getDataSwingManager();
400
//                SearchPostProcessFactory factory= manager.getSearchPostProcess(this.panel.currentPostProcess);
401
//                SearchParameters searchParams =this.panel.parameters.getCopy();
402
//                if (factory.hasProcessParameters()){
403
//                    SearchPostProcess.SearchPostProcessResult searchPostProcessResult = this.panel.doExecuteSearchPostProcess(this.panel.store, this.panel.parameters.getQuery(), factory, this.panel.postProcessParams, searchParams);
404
//                    return searchPostProcessResult.getQuery();
405
//                }
406
//                SearchPostProcess.SearchPostProcessResult searchPostProcessResult = this.panel.doExecuteSearchPostProcess(this.panel.store, this.panel.parameters.getQuery(), factory, null, searchParams);
407
//                return searchPostProcessResult.getQuery();
408
            }
409
        }
410
    }
411

    
412
//    private class SearchPostProcessListener implements ActionListener {
413
//
414
//        private final FeatureStore input;
415
//        private final SearchPostProcessFactory factory;
416
//        private final FeatureQuery query;
417
//
418
//        public SearchPostProcessListener(
419
//                FeatureStore input,
420
//                FeatureQuery query,
421
//                SearchPostProcessFactory factory
422
//        ) {
423
//            this.input = input;
424
//            this.query = query;
425
//            this.factory = factory;
426
//        }
427
//
428
//        @Override
429
//        public void actionPerformed(ActionEvent e) {
430
//            // habilita la pesta�a del tab con los resultados del post procesado
431
//            if (this.factory.hasProcessParameters()) {
432
//                DynObject parameters = this.factory.createProcessParameters(this.input);
433
//                JDynForm form = DynFormLocator.getDynFormManager().createJDynForm(parameters);
434
//                form.asJComponent().setPreferredSize(new Dimension(350, 250));
435
//
436
//                I18nManager i18n = ToolsLocator.getI18nManager();
437
//                WindowManager_v2 windowManager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
438
//
439
//                Dialog dialog = windowManager.createDialog(
440
//                        form.asJComponent(),
441
//                        i18n.getTranslation("_create_parameters"),
442
//                        i18n.getTranslation("_parameters_list"),
443
//                        WindowManager_v2.BUTTONS_OK_CANCEL);
444
//
445
//                dialog.addActionListener((ActionEvent e2) -> {
446
//                    if (dialog.getAction() == WindowManager_v2.BUTTON_OK) {
447
//                        form.getValues(parameters); // actualiza el valor de lo los parametros con los valores introducidos por el usuario
448
//                        doExecuteSearchPostProcess(this.input, this.query, this.factory, parameters);
449
//                        postProcessParams = parameters;
450
//                    }
451
//                });
452
//
453
//                dialog.show(WindowManager.MODE.DIALOG);
454
//
455
//            } else {
456
//                doExecuteSearchPostProcess(this.input, this.query, this.factory, null);
457
//            }
458
//        }
459
//    }
460

    
461
    private FeatureStore store;
462
    private final ActionListenerSupport acctionListeners;
463
    private final Map<String, ActionButtons> actions;
464
    private boolean showActions = true;
465
    private DefaultSearchParameters parameters;
466

    
467
    private List<SearchConditionPanel> conditionPanels;
468

    
469
    public static final int PANEL_SIMPLIFIED = 0;
470
    public static final int PANEL_ADVANCED = 1;
471
    private static final String BOOKMARKSANDHISTORY_NAME = "SearchPanel";
472
    private final Bookmarks<Object> bookmarks;
473
    private final History<Object> history;
474
    private boolean filterOnlyMode;
475

    
476
    private String currentPostProcess;
477

    
478
    private DynObject postProcessParams;
479
    private FeatureStore postProcessStore;
480
    private FeatureQuery postProcessQuery;
481
    private SimpleFeaturesTableModel resultModel;
482
    private SimpleFeaturesTableModel resultPostProcessModel;
483

    
484
    private boolean processing;
485
    private JComponent configurableActions;
486

    
487
    @SuppressWarnings({"OverridableMethodCallInConstructor", "LeakingThisInConstructor"})
488
    public DefaultSearchPanel(FeatureStore store) {
489
        this.store = store;
490
        this.filterOnlyMode = false;
491
        DisposeUtils.bind(store);
492
        this.acctionListeners = ToolsSwingLocator.getToolsSwingManager().createActionListenerSupport();
493
        this.actions = new HashMap<>();
494
        this.parameters = new DefaultSearchParameters();
495
        FeatureQuery featureQuery = this.store.createFeatureQuery();
496
        featureQuery.retrievesAllAttributes();
497
        this.parameters.setQuery(featureQuery);
498
        this.currentPostProcess = null;
499
        this.postProcessParams = null;
500
        this.postProcessStore = null;
501
        this.postProcessQuery = null;
502
        this.processing = false;
503
        this.configurableActions = null;
504
        this.resultModel = null;
505
        this.resultPostProcessModel = null;
506
        this.propertiesHelper = new PropertiesSupportHelper();
507
        this.propertiesHelper.setProperty("SearchPanel", this);
508

    
509
        Search search = (Search) ToolsLocator.getComplementsManager().get(
510
                Search.COMPLEMENT_MANE, getFeatureType()
511
        );
512
        List<Search.OrderedAttribute> attributos = search.getOrderedAttributes(
513
                Search.BASIC_TYPES_FILTER,
514
                Search.STR_INT_LONG_LABEL_ORDER,
515
                12
516
        );
517
        for (Search.OrderedAttribute attrdesc : attributos) {
518
            this.parameters.getResultColumnNames().add(attrdesc.getDescriptor().getName());
519
        }
520
        this.bookmarks = ToolsLocator.getBookmarksAndHistoryManager().getBookmarksGroup(BOOKMARKSANDHISTORY_NAME);
521
        this.history = ToolsLocator.getBookmarksAndHistoryManager().getHistoryGroup(BOOKMARKSANDHISTORY_NAME);
522
    }
523

    
524
    @Override
525
    public void dispose() {
526
        DisposeUtils.disposeQuietly(store);
527
        TableModel m = this.tblResults.getModel();
528
        if (m instanceof Disposable) {
529
            DisposeUtils.disposeQuietly((Disposable) m);
530
        }
531
        this.store = null;
532
        this.tblResults.setModel(new DefaultTableModel());
533
    }
534

    
535
    @Override
536
    public JComponent asJComponent() {
537
        if (this.conditionPanels == null) {
538
            this.initComponents();
539
        }
540
        return this;
541
    }
542

    
543
    private void addActions() {
544
        if (!this.showActions) {
545
            return;
546
        }
547
        this.pnlActions.removeAll();
548
        this.pnlActions.setLayout(new FlowLayout(FlowLayout.TRAILING, 8, 4));
549
        SearchActionContext actionContext = new SearchActionContext(this);
550
        Collection<DALActionFactory> factories = DALSwingLocator.getSwingManager().getStoreActions();
551
        for (DALActionFactory factory : factories) {
552
            if (!factory.isApplicable(actionContext)) {
553
                continue;
554
            }
555
            Action action = factory.createAction(actionContext);
556
            JButton button = new JButton(action);
557
            this.actions.put(factory.getName(), new ActionButtons(factory, action, button));
558
            button.setBorder(BorderFactory.createEmptyBorder());
559
            button.setBorderPainted(false);
560
            button.setFocusPainted(false);
561
            button.setContentAreaFilled(false);
562
            button.setCursor(new Cursor(Cursor.HAND_CURSOR));
563
            this.pnlActions.add(button);
564
        }
565
        this.pnlActions.revalidate();
566
        this.pnlActions.repaint();
567
    }
568

    
569
    @Override
570
    public void addActionListener(ActionListener listener) {
571
        this.acctionListeners.addActionListener(listener);
572
    }
573

    
574
    @Override
575
    public ActionListener[] getActionListeners() {
576
        return this.acctionListeners.getActionListeners();
577
    }
578

    
579
    @Override
580
    public void removeActionListener(ActionListener listener) {
581
        this.acctionListeners.removeActionListener(listener);
582
    }
583

    
584
    @Override
585
    public void removeAllActionListener() {
586
        this.acctionListeners.removeAllActionListener();
587
    }
588

    
589
    @Override
590
    public void fireActionEvent(ActionEvent event) {
591
        this.acctionListeners.fireActionEvent(event);
592
    }
593

    
594
    @Override
595
    public boolean hasActionListeners() {
596
        return this.acctionListeners.hasActionListeners();
597
    }
598

    
599
    private void initComponents() {
600
        this.conditionPanels = new ArrayList<>();
601

    
602
        ToolsSwingManager swingManager = ToolsSwingLocator.getToolsSwingManager();
603
        swingManager.translate(this.tabSearchMode);
604
        swingManager.translate(this.tabResults);
605
        swingManager.translate(this.btnSearch);
606
        swingManager.translate(this.btnClear);
607
        swingManager.translate(this.btnSearchPostProcess);
608
        swingManager.translate(this.lblExpressionDeBusqueda);
609
        swingManager.translate(this.btnAddAccumulatedFilter);
610
        swingManager.translate(this.btnRemoveAccumulatedFilter);
611
        swingManager.translate(this.btnViewAccumulatedFilter);
612
        
613
        ConfigurableActionsMamager cfgActionsManager = ToolsUtilLocator.getConfigurableActionsMamager();
614
        this.configurableActions = cfgActionsManager.getConfigurableActionsComponent(CONFIGURABLE_PANEL_ID, this);
615
        this.pnlCfgActions.setLayout(new BorderLayout(0, 0));
616
        this.pnlCfgActions.add(configurableActions, BorderLayout.CENTER);
617
        
618
        this.taskStatusController = ToolsSwingLocator.getTaskStatusSwingManager().createTaskStatusController(
619
                this.lblStatusTitle, 
620
                this.lblMsg, 
621
                this.pgbStatus);
622
                this.pgbStatus.setVisible(false);
623

    
624
        this.conditionPanels.add(
625
                new SearchConditionPanelSimplified(
626
                        parameters,
627
                        store,
628
                        btnAddAccumulatedFilter,
629
                        btnRemoveAccumulatedFilter,
630
                        btnViewAccumulatedFilter,
631
                        lblField1,
632
                        lblExtraFields1,
633
                        lblRelationalOperator1,
634
                        cboValue1,
635
                        lblNull1,
636
                        lblLogicalOperators1,
637
                        lblField2,
638
                        lblExtraFields2,
639
                        lblRelationalOperator2,
640
                        cboValue2,
641
                        lblNull2,
642
                        lblLogicalOperators2,
643
                        lblField3,
644
                        lblExtraFields3,
645
                        lblRelationalOperator3,
646
                        cboValue3,
647
                        lblNull3,
648
                        lblLogicalOperators3,
649
                        lblField4,
650
                        lblExtraFields4,
651
                        lblRelationalOperator4,
652
                        cboValue4,
653
                        lblNull4,
654
                        null
655
                )
656
        );
657
        
658
        SearchConditionPanelAdvanced advancedPanel = new SearchConditionPanelAdvanced(
659
                this.store,
660
                txtAdvancedExpression,
661
                btnAdvancedExpression,
662
                btnAdvancedExpressionHistory,
663
                btnAdvancedExpressionBookmarks
664
        );
665
        this.conditionPanels.add(advancedPanel);
666
        
667
        for (SearchConditionPanelFactory factory : DALSwingLocator.getManager().getSearchConditionPanels()) {
668
            String factoryName = "unknown";
669
            try {
670
                factoryName = factory.getName();
671
                if (factory.isApplicable(store)) {
672
                    SearchConditionPanel panel = factory.create(this);
673
                    this.conditionPanels.add(panel);
674
                    this.tabSearchMode.add(factory.getName(), panel.asJComponent());
675
                }
676
            } catch (Throwable th) {
677
                LOGGER.warn("Can't create search panel '" + factoryName + "'.");
678
            }
679
        }
680

    
681
        this.btnSearch.addActionListener((ActionEvent e) -> {
682
            this.tabResults.setEnabledAt(1, false);
683
            search();
684
        });
685

    
686
        this.tblResults.getSelectionModel().addListSelectionListener((ListSelectionEvent e) -> {
687
            try {
688
                lastSelectedFeature = resultModel.getFeatureAt(tblResults.getSelectedRow());
689
            } catch(Throwable th ) {
690
                LOGGER.debug("Can't retrieve last selected feature.",th);
691
            }
692
            for (ActionButtons actionButton : actions.values()) {
693
                if (actionButton.action instanceof ListSelectionListener) {
694
                    ((ListSelectionListener) actionButton.action).valueChanged(e);
695
                }
696
            }
697
        });
698
        this.btnClear.addActionListener((ActionEvent e) -> {
699
            clear();
700
        });
701
        addActions();
702

    
703
        //swingManager.createTableColumnAdjuster(tblResults);
704
        //swingManager.createTableColumnAdjuster(tblSearchPostProcessResults);
705

    
706
//        this.setPreferredSize(new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT));
707
        ToolsSwingUtils.ensureRowsCols(this, 20, 100, 30, 120);
708

    
709
        this.bookmarksController = ToolsSwingLocator.getToolsSwingManager().createBookmarksController(this.bookmarks, btnBookmarks);
710
        this.historyController = ToolsSwingLocator.getToolsSwingManager().createHistoryController(this.history, btnHistory);
711

    
712
        this.historyController.setFilter(null);
713

    
714
        ActionListener bookmarksAndHistoryListener = (ActionEvent e) -> {
715
            ActionEventWithCurrentValue<DefaultSearchParameters> b = (ActionEventWithCurrentValue<DefaultSearchParameters>) e;
716
            switch (b.getID()) {
717
                case ID_GETVALUE:
718
                    DefaultSearchParameters actualParams = (DefaultSearchParameters) fetch(null);
719
                    b.setCurrentValue(actualParams);
720
                    break;
721
                    
722
                case ID_SETVALUE:
723
                    if (b.getCurrentValue() == null) {
724
                        return;
725
                    }
726
                    DefaultSearchParameters searchParams;
727
                    try {
728
                        searchParams = b.getCurrentValue().getCopy();
729
                    } catch (Exception ex) {
730
                        LOGGER.warn("Not been able to clone export parameters", ex);
731
                        return;
732
                    }
733
                    clear();
734
                    put(searchParams);
735
                    Thread th = new Thread(() -> {
736
                        doSearch(searchParams);
737
                    });
738
                    th.start();
739
                    break;
740
            }
741
        };
742
        this.historyController.addActionListener(bookmarksAndHistoryListener);
743
        this.bookmarksController.addActionListener(bookmarksAndHistoryListener);
744
        this.addComponentListener(new ComponentAdapter() {
745
            @Override
746
            public void componentHidden(ComponentEvent e) {
747
                dispose();
748
            }
749
        });
750

    
751
        this.btnSearchPostProcess.addActionListener((ActionEvent e) -> {
752
            try {
753
                doSelectSearchPostprocess();
754
            } catch (DataException ex) {
755
                LOGGER.warn("Can't select a Search Post Process", ex);
756
            }
757
        });
758

    
759
        this.tabResults.setEnabledAt(1, false);
760

    
761
        this.tblResults.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
762
        this.tblResults.addKeyListener(new KeyAdapter() {
763
            @Override
764
            public void keyPressed(KeyEvent e) {
765
                if( e.getKeyCode()==KeyEvent.VK_F4 ) {
766
                    doShowCellInDialog();
767
                }
768
            }
769
        });        
770
        
771
        this.tblResults.setComponentPopupMenu(new TablePopupMenu(this.tblResults));
772
        this.tblSearchPostProcessResults.setComponentPopupMenu(new TablePopupMenu(this.tblSearchPostProcessResults));
773
                
774
        //this.tblResults.add
775
        if (this.bookmarks.hasBookmark(this.store.getName())) {
776
            Bookmark<DefaultSearchParameters> initBookmark = this.bookmarks.get(this.store.getName());
777
            DefaultSearchParameters initSearchParams = initBookmark.getValue().getCopy();
778
            put(initSearchParams);
779
            Thread th = new Thread(() -> {
780
                doSearch(initSearchParams);
781
            });
782
            th.start();
783
            return;
784
        }
785
        
786
        this.tabResults.addChangeListener((ChangeEvent evt) -> {
787
            SwingUtilities.invokeLater(() -> {
788
                if(tabResults.getSelectedIndex()==0){
789
                    updateNumberElementsMsg(resultModel);
790
                }else{
791
                    updateNumberElementsMsg(resultPostProcessModel);
792
                }
793
            });
794
        });
795
        if( this.filterOnlyMode ) {
796
            this.btnSearchPostProcess.setVisible(false);
797
        }
798
        clear();
799
        search();
800
    }
801
    
802
    private void doShowCellInDialog() {
803
        int row = this.tblResults.getSelectedRow();
804
        if( row < 0 ) {
805
            return;
806
        }
807
        int col = this.tblResults.getSelectedColumn();
808
        if( col < 0 ) {
809
            return;
810
        }
811
        String s = Objects.toString(this.tblResults.getValueAt(row, col),null);
812
        if( StringUtils.isBlank(s) ) {
813
            return;
814
        }
815
        ToolsSwingLocator.getToolsSwingManager().showZoomDialog(
816
            this, 
817
            this.tblResults.getColumnName(col), 
818
            s,
819
            false
820
        );
821
    }
822

    
823
    @Override
824
    public FeatureType getFeatureType() {
825
        try {
826
            return store.getDefaultFeatureType();
827
        } catch (Exception ex) {
828
            throw new RuntimeException("Can't retrieve the feature type.", ex);
829
        }
830
    }
831

    
832
    @Override
833
    public void setEnabled(boolean enabled) {
834
        if(!SwingUtilities.isEventDispatchThread()) {
835
            SwingUtilities.invokeLater(() -> {setEnabled(enabled);});
836
            return;
837
        }
838
        
839
        if (this.conditionPanels == null) {
840
            this.initComponents();
841
        }
842
        for (SearchConditionPanel conditionPanel : conditionPanels) {
843
            conditionPanel.setEnabled(enabled);
844
        }
845

    
846
        this.btnClear.setEnabled(enabled);
847
        this.btnSearch.setEnabled(enabled);
848
        for (ActionButtons actionButton : actions.values()) {
849
            actionButton.action.setEnabled(enabled);
850
        }
851
        this.btnSearchPostProcess.setEnabled(enabled);
852
        //bookmarkController,historyController,configurableActions
853
    }
854

    
855
    @Override
856
    public void clear() {
857
        this.taskStatusController.setTitle("");
858
        if (this.conditionPanels == null) {
859
            return;
860
        }
861
        for (SearchConditionPanel conditionPanel : conditionPanels) {
862
            conditionPanel.clear();
863
        }
864
        FeatureQuery emptyQuery = this.store.createFeatureQuery();
865
        emptyQuery.retrievesAllAttributes();
866
        this.parameters.setQuery(emptyQuery);
867
        // Mantener las columnas visualizadas
868
        // Elimina las que no existen en el store como campos calculados que
869
        // pudieran existir en el fquery
870
        List<String> resultColumnNames = this.parameters.getResultColumnNames();
871
        ArrayList<String> toDeleteAlreadyDontExist = new ArrayList<>();
872
        for (String resultColumnName : resultColumnNames) {
873
            try {
874
                FeatureAttributeDescriptor attr = this.store.getDefaultFeatureType().getAttributeDescriptor(resultColumnName);
875
                if (attr == null) {
876
                    toDeleteAlreadyDontExist.add(resultColumnName);
877
                }
878
            } catch (DataException ex) {
879

    
880
            }
881
        }
882
        resultColumnNames.removeAll(toDeleteAlreadyDontExist);
883
        resetTable();
884
    }
885

    
886
    @Override
887
    public FeatureQuery getLastQuery() {
888
        return this.lastQuery;
889
    }
890

    
891
    public boolean isValid(StringBuilder message) {
892
        int searchMode = this.tabSearchMode.getSelectedIndex();
893
        SearchConditionPanel panel = this.conditionPanels.get(searchMode);
894
        boolean valid = panel.isValid(message);
895
        return valid;
896
    }
897
    
898
    @Override
899
    public void search() {
900
        StringBuilder message = new StringBuilder();
901
        if (!this.isValid(message)) {
902
            ThreadSafeDialogsManager dialogManager = ToolsSwingLocator.getThreadSafeDialogsManager();
903
            dialogManager.messageDialog(
904
                    "_The_specified_search_condition_is_not_valid",
905
                    "_Search",
906
                    JOptionPane.WARNING_MESSAGE
907
            );
908
            return;
909
        }
910
        lblMsg.setText(ToolsLocator.getI18nManager().getTranslation("_Searching")+"...");
911
        setEnabled(false);
912
        Thread th = new Thread(() -> {
913
        try {
914
                                SearchParameters searchParams;
915
                                try {
916
                                        searchParams = this.fetch(this.parameters.getCopy()); // esto lo actualiza a la ultima // decidir si se devuelve clonado
917

    
918
                                        Date date = Calendar.getInstance().getTime();
919
                                        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
920
                                        String strDate = dateFormat.format(date);
921
                                        searchParams.setName("Params: " + strDate);
922
                                } catch (Exception ex) {
923
                                        LOGGER.warn("Not able to create search parameters.", ex);
924
                                        this.taskStatusController.setTitle(ToolsLocator.getI18nManager().getTranslation("_Errors_fetching_new_query") + "...");
925
                                        resetTable();
926
                                        return;
927
                                }
928
                                doSearch(searchParams);
929
                        } catch (Exception ex) {
930
                                LOGGER.warn("Search panel has errors during the search", ex);
931
                                resetTable();
932
                        } finally {
933
                                SwingUtilities.invokeLater(() -> {
934
                                        setEnabled(true);
935
                                });
936
                        }
937
        });
938
        th.start();
939
    }
940
    
941
    private void doSearch(SearchParameters searchParams)  {
942
            final MutableObject model = new MutableObject(null);       
943
            final MutableLong rowCount=new MutableLong();
944
                        Cursor savedCursor = this.getCursor();
945
                    SimpleTaskStatus status = ToolsLocator.getTaskStatusManager().createDefaultSimpleTaskStatus("");
946
                        status.setAutoremove(true);
947
                        status.add();
948
                        this.taskStatusController.bind(status);
949
            try {
950
                                status.setTitle(ToolsLocator.getI18nManager().getTranslation("_Processing_search"));
951
                                SwingUtilities.invokeLater(() -> {this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));});
952
                final List<Feature> features;
953
                 FeatureQuery myQuery;
954
//                myQuery = this.getQuery().getCopy();
955
                this.tabResults.setSelectedIndex(0);
956
                List<String> resultColumnNames = searchParams.getResultColumnNames();
957
                myQuery = searchParams.getQuery().getCopy();
958
                features = store.getFeatures(myQuery, 50);
959
                FacadeOfAFeaturePagingHelper facade = (FacadeOfAFeaturePagingHelper) features;
960
                FeatureType ftype = facade.getFeaturePagingHelper().getFeatureSet().getDefaultFeatureType();
961
                // al modelo le pasamos el ftype de esas features
962
                SimpleFeaturesTableModel tableModel = new SimpleFeaturesTableModelImpl(
963
                        ftype,
964
                        resultColumnNames,
965
                        features
966
                );
967
                model.setValue(tableModel);
968
                rowCount.setValue(tableModel.getRowCount());
969
            } catch (Exception ex) {
970
                LOGGER.warn("Search not able to be executed. Can't get features or create table model", ex);
971
                status.setTitle(ToolsLocator.getI18nManager().getTranslation("_Errors_getting_new_feature_set") + "...");
972
                                status.abort();
973
                resetTable();
974
            } finally {
975
                SwingUtilities.invokeLater(() -> {
976
                    I18nManager i18n = ToolsLocator.getI18nManager();
977
                    try {
978
                        TableModel oldmodel = tblResults.getModel();
979
                        resultModel = (SimpleFeaturesTableModel) model.getValue();
980
                        tblResults.setModel(resultModel);
981
                        resultModel.setCellRenderers(tblResults,getCustomRenderers(searchParams));
982
                        if (oldmodel instanceof SimpleFeaturesTableModelImpl) {
983
                            ((SimpleFeaturesTableModelImpl) oldmodel).dispose();
984
                        }
985
                        if (resultModel.hasErrors()) {
986
                            status.setTitle(i18n.getTranslation("_Errors_occurred_during_search"));
987
                        } else {
988
                            status.setTitle(String.format("%d " + i18n.getTranslation("_elements"), rowCount.getValue()));
989
                        }
990
                        if (this.parameters != null && this.parameters.getQuery() != null) {
991
                            this.history.add(searchParams);                   
992
                        }
993
                    } catch (Exception ex) {
994
                        LOGGER.warn(" Errors occurred during search getting old model", ex);
995
                        status.setTitle(i18n.getTranslation("_Errors_occurred_during_search"));
996
                    } finally {
997
                        setEnabled(true);
998
                                                status.terminate();
999
                                                this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
1000
                    }
1001
                });
1002
            }
1003
     }
1004
    
1005
    private Map<String, TableCellRenderer> getCustomRenderers(SearchParameters parameters) {
1006
        FeatureType ft = this.store.getDefaultFeatureTypeQuietly();
1007
        HashMap<String, TableCellRenderer> renderers = new HashMap<String, TableCellRenderer>();
1008
        for (FeatureAttributeDescriptor attr : ft) {
1009
            if(attr.getDataType().isNumeric()) {
1010
//                renderers.put(attr.getName(), new ColorRangeRenderer(attr, 20, 50));
1011
            }
1012
        }
1013
        return renderers;
1014
    }
1015

    
1016
    private void resetTable() {
1017
        if(!SwingUtilities.isEventDispatchThread()) {
1018
            SwingUtilities.invokeLater(this::resetTable);
1019
            return;
1020
        }
1021
        List<String> resultColumnNames = null;
1022
        try {
1023
            resultColumnNames = this.parameters.getResultColumnNames();
1024
        } catch(Exception ex) {
1025
            
1026
        }
1027
        FeatureType ftype = this.store.getDefaultFeatureTypeQuietly();
1028
        SimpleFeaturesTableModelImpl emptyTableModel = new SimpleFeaturesTableModelImpl(
1029
                ftype,
1030
                resultColumnNames,
1031
                null
1032
        );
1033
        this.tblResults.setModel(emptyTableModel);
1034
        
1035
    }
1036

    
1037
    public void setResultColumnNames(List<String> names) { 
1038
        this.parameters.getResultColumnNames().clear();
1039
        this.parameters.getResultColumnNames().addAll(names);
1040
//        if (this.conditionPanels == null) {
1041
//            return;
1042
//        }
1043
//        SimpleFeaturesTableModelImpl model;
1044
////        model = (SimpleFeaturesTableModel) this.tblResults.getModel();
1045
//        List<Feature> features = store.getFeatures(this.parameters.getQuery());
1046
//        FacadeOfAFeaturePagingHelper facade = (FacadeOfAFeaturePagingHelper) features;
1047
//        FeatureType ftype = facade.getFeaturePagingHelper().getFeatureSet().getDefaultFeatureType();
1048
//        model = new SimpleFeaturesTableModelImpl(
1049
//                ftype,
1050
//                this.parameters.getResultColumnNames(),
1051
//                features
1052
//        );
1053
//        tblResults.setModel(model);
1054
    }
1055

    
1056
    @Override
1057
    public boolean setFilter(Expression filter) {
1058
        try {
1059
            if (this.conditionPanels == null) {
1060
                this.initComponents();
1061
            }
1062
            if (ExpressionUtils.isPhraseEmpty(filter)) {
1063
                this.clear();
1064
                return true;
1065
            }
1066
            int panel = 0;
1067
            int selected = PANEL_ADVANCED;
1068
            for (SearchConditionPanel conditionPanel : conditionPanels) {
1069
                if (panel != PANEL_ADVANCED && conditionPanel.set(filter)) {
1070
                    selected = panel;
1071
                }
1072
                panel++;
1073
            }
1074
            this.tabSearchMode.setSelectedIndex(selected);
1075

    
1076
//            SimpleFeaturesTableModel model = new SimpleFeaturesTableModel(this.getStore());
1077
//            tblResults.setModel(model);
1078
//            lblMsg.setText("");
1079
            return true;
1080
        } catch (Exception ex) {
1081
            LOGGER.warn("Can't set current search", ex);
1082
            return false;
1083
        }
1084
    }
1085

    
1086
    @Override
1087
    public List<SearchConditionPanel> getConditionPanels() {
1088
        return Collections.unmodifiableList(this.conditionPanels);
1089
    }
1090

    
1091
    @Override
1092
    public SearchConditionPanel getConditionPanel(String name) {
1093
        if( conditionPanels==null ) {
1094
            return null;
1095
        }
1096
        for (SearchConditionPanel panel : conditionPanels) {
1097
            if (StringUtils.equalsIgnoreCase(name, panel.getFactory().getName())) {
1098
                return panel;
1099
            }
1100
        }
1101
        return null;
1102
    }
1103

    
1104

    
1105
 @Override
1106
    public Expression getFilterForSelectedFeature() {
1107
        if (this.conditionPanels == null) {
1108
            return null;
1109
        }
1110
        if (this.tabResults.getSelectedIndex() == 0) {
1111
            int selectedRow = this.tblResults.getSelectedRow();
1112
            if (selectedRow < 0) {
1113
                return null;
1114
            }
1115
            try {
1116
                List<Feature> features = ((SimpleFeaturesTableModelImpl) this.tblResults.getModel()).getFeatures();
1117
                Feature feature = features.get(selectedRow);
1118

    
1119
                ExpressionBuilder builder = ExpressionUtils.createExpressionBuilder();
1120
                FeatureType ftype = this.store.getDefaultFeatureType();
1121
                for (FeatureAttributeDescriptor attrdesc : ftype.getPrimaryKey()) {
1122
                    builder.and(
1123
                            builder.eq(
1124
                                    builder.column(attrdesc.getName()),
1125
                                    builder.constant(feature.get(attrdesc.getName()))
1126
                            )
1127
                    );
1128
                }
1129
                Expression filter = ExpressionUtils.createExpression(builder.toString());
1130
                return filter;
1131
            } catch (Exception ex) {
1132
                LOGGER.warn("Can't build search for the selected feature.", ex);
1133
                return null;
1134
            }
1135
        } else {
1136
            if (this.currentPostProcess == null) {
1137
                return null;
1138
            }
1139
            int selectedRow = this.tblSearchPostProcessResults.getSelectedRow();
1140
            if (selectedRow < 0) {
1141
                return null;
1142
            }
1143
            try {
1144
                List<Feature> features = ((SimpleFeaturesTableModelImpl) this.tblSearchPostProcessResults.getModel()).getFeatures();
1145
                Feature feature = features.get(selectedRow);
1146

    
1147
                ExpressionBuilder builder = ExpressionUtils.createExpressionBuilder();
1148
                FeatureType ftype = this.postProcessStore.getDefaultFeatureType();
1149
                for (FeatureAttributeDescriptor attrdesc : ftype.getPrimaryKey()) {
1150
                    builder.and(
1151
                            builder.eq(
1152
                                    builder.column(attrdesc.getName()),
1153
                                    builder.constant(feature.get(attrdesc.getName()))
1154
                            )
1155
                    );
1156
                }
1157
                Expression filter = ExpressionUtils.createExpression(builder.toString());
1158
                return filter;
1159
            } catch (Exception ex) {
1160
                LOGGER.warn("Can't build search for the selected feature.", ex);
1161
                return null;
1162
            }
1163
        }
1164

    
1165
    }
1166
    
1167
    @Override
1168
    public FeatureStore getStore() {
1169
        return store;
1170
    }
1171

    
1172
    private void doOrderBy() {
1173
        I18nManager i18n = ToolsLocator.getI18nManager();
1174
        WindowManager_v2 windowManager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
1175
        FeatureQueryOrderPanel orderPanel = DALSwingLocator.getDataSwingManager().createFeatureStoreOrderPanel();
1176
        orderPanel.setStore(store);
1177
        orderPanel.put(parameters.getQuery());
1178
        Dialog dialog = windowManager.createDialog(
1179
                orderPanel.asJComponent(),
1180
                i18n.getTranslation("_Select_order"),
1181
                null,
1182
                WindowManager_v2.BUTTONS_OK_CANCEL
1183
        );
1184
        dialog.addActionListener((ActionEvent e) -> {
1185
            if (dialog.getAction() == WindowManager_v2.BUTTON_OK) {
1186
                orderPanel.fetch(this.parameters.getQuery());
1187
                search();
1188
            }
1189
        });
1190
        dialog.show(WindowManager.MODE.DIALOG);
1191
    }
1192
       
1193
    private void doCopyRows(JTable table) {
1194
        Cursor savedCursor = this.getCursor();
1195
        SimpleTaskStatus status = ToolsLocator.getTaskStatusManager().createDefaultSimpleTaskStatus("");
1196
        status.setAutoremove(true);
1197
        status.add();
1198
        this.taskStatusController.bind(status);
1199
        Thread task = new Thread(() -> {
1200
            try {
1201
                this.processing = true;
1202
                this.setEnabled(false);
1203
                                status.setTitle(ToolsLocator.getI18nManager().getTranslation("_Copying_rows_to_clipboard"));
1204
                SwingUtilities.invokeLater(() -> {this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));});
1205

    
1206
                SimpleFeaturesTableModel model = null;
1207
                if (table.getModel() instanceof SimpleFeaturesTableModel) {
1208
                    model = (SimpleFeaturesTableModel) table.getModel();
1209
                }
1210

    
1211
                String LINE_BREAK = System.lineSeparator();
1212
                String CELL_BREAK = "\t";
1213
                char DELIMITER = '"';
1214

    
1215

    
1216
                int[] selection = table.getSelectedRows();
1217
                for (int i = 0; i < selection.length; i++) {
1218
                    selection[i] = table.convertRowIndexToModel(selection[i]);
1219
                }
1220

    
1221
                int numCols = table.getColumnCount();
1222
                StringBuilder excelStr = new StringBuilder();
1223
                boolean valueIsNumeric;
1224

    
1225
                for (int j = 0; j < numCols; j++) {
1226

    
1227
                    excelStr.append(DELIMITER);
1228
                    excelStr.append(escape(table.getColumnName(j), LINE_BREAK, CELL_BREAK));
1229
                    excelStr.append(DELIMITER);
1230

    
1231
                    if (j < numCols - 1) {
1232
                        excelStr.append(CELL_BREAK);
1233
                    }
1234
                }
1235

    
1236
                //from( 0, selection.length)
1237

    
1238
                status.setRangeOfValues(0, selection.length);
1239
                excelStr.append(LINE_BREAK);
1240
                for (int i : selection) {
1241
                    if(status.isCancellationRequested()) {
1242
                        status.message("");
1243
                        status.cancel();
1244
                        return;
1245
                    }
1246
                    for (int j = 0; j < numCols; j++) {
1247
                        valueIsNumeric = false;
1248
                        FeatureAttributeDescriptor descriptor = null;
1249
                        if (model != null) {
1250
                            descriptor = model.getFeatureDescriptor(j);
1251
                            if (descriptor.getDataType().isNumeric()) {
1252
                                if (!descriptor.hasAvailableValues()) {
1253
                                    valueIsNumeric = true;
1254
                                }
1255
                            }
1256
                        }
1257
                        if (!valueIsNumeric) {
1258
                            excelStr.append(DELIMITER);
1259
                        }
1260
                        Object value = table.getValueAt(i, j);
1261
                        String valueStr;
1262
                        if (descriptor != null) {
1263
                            valueStr = escape(descriptor.format(value), LINE_BREAK, CELL_BREAK);
1264
                        } else {
1265
                            valueStr = escape(value, LINE_BREAK, CELL_BREAK);
1266

    
1267
                        }
1268
                        excelStr.append(valueStr);
1269

    
1270
                        if (!valueIsNumeric) {
1271
                            excelStr.append(DELIMITER);
1272
                        }
1273
                        if (j < numCols - 1) {
1274
                            excelStr.append(CELL_BREAK);
1275
                        }
1276
                    }
1277
                    status.setCurValue(i);
1278
                    excelStr.append(LINE_BREAK);
1279
                }
1280
                String toStr = excelStr.toString();
1281

    
1282
                status.terminate();
1283
                doPostCopyRows(status, toStr);
1284

    
1285
            } catch (Exception ex) {
1286
                LOGGER.warn("Not able to copy rows to the clipboard", ex);
1287
                status.message("Not able to copy rows to the clipboard");
1288
                status.abort();
1289
            } finally {
1290
                this.processing = false;
1291
                SwingUtilities.invokeLater(() -> {this.setCursor(savedCursor);});
1292
                                status.setTitle(ToolsLocator.getI18nManager().getTranslation("_Copy_ended"));
1293
                this.updateComponentState();
1294
            }
1295
        }, "SearchPanelCopyRows");
1296
        task.start();
1297
    }
1298
    
1299
    private void doPostCopyRows(SimpleTaskStatus status, String toStr) {
1300
        if(!SwingUtilities.isEventDispatchThread()) {
1301
            SwingUtilities.invokeLater(() -> {doPostCopyRows(status, toStr);});
1302
            return;
1303
        }
1304
        ToolsSwingLocator.getToolsSwingManager().putInClipboard(toStr);
1305
//        StringSelection sel = new StringSelection(toStr);
1306
//        Clipboard CLIPBOARD = Toolkit.getDefaultToolkit().getSystemClipboard();
1307
//        CLIPBOARD.setContents(sel, null);            
1308
    }
1309

    
1310
    private String escape(Object cell,String LINE_BREAK, String CELL_BREAK) {
1311
        return (cell == null ? "" : cell.toString()
1312
                .replace(CELL_BREAK, " ")
1313
                .replace("\n", " ")
1314
                .replace("\r", " ")
1315
                );
1316
    }
1317
       
1318
    @Override
1319
    public ImageIcon loadImage(String imageName) {
1320
        String name = FilenameUtils.getBaseName(imageName);
1321
        IconTheme theme = ToolsSwingLocator.getIconThemeManager().getDefault();
1322
        if (theme.exists(name)) {
1323
            return theme.get(name);
1324
        }
1325
        URL url = this.getClass().getResource(name + ".png");
1326
        if (url == null) {
1327
            return null;
1328
        }
1329
        return new ImageIcon(url);
1330
    }
1331

    
1332
    @Override
1333
    public int getSelectedFeatureCount() {
1334
        if (this.conditionPanels == null) {
1335
            return 0;
1336
        }
1337
        if (this.currentPostProcess == null || this.tabResults.getSelectedIndex() == 0) {
1338
            return this.tblResults.getSelectedRowCount();
1339
        }
1340
        return this.tblSearchPostProcessResults.getSelectedRowCount();
1341
    }
1342

    
1343
    @Override
1344
    public JComponent getActionButton(String name) {
1345
        ActionButtons actionButton = this.actions.get(name);
1346
        if (actionButton == null) {
1347
            return null;
1348
        }
1349
        return actionButton.button;
1350
    }
1351

    
1352
    @Override
1353
    public void setShowActions(boolean showActions) {
1354
        this.showActions = showActions;
1355
    }
1356

    
1357
    @Override
1358
    public boolean isShowActions() {
1359
        return this.showActions;
1360
    }
1361

    
1362
    public static String getAttributeDescriptorLabel(FeatureAttributeDescriptor attrdesc, String tableName) {
1363
        String theLabel;
1364
        int theUseLabels;
1365
        if (useLabels == null) {
1366
            Tags tags = attrdesc.getTags();
1367
            if (tags.has(DAL_USE_LABELS)) {
1368
                theUseLabels = tags.getInt(DAL_USE_LABELS, USE_LABELS_NO);
1369
            } else {
1370
                if (attrdesc.getFeatureType()!=null) {
1371
                    tags = attrdesc.getFeatureType().getTags();
1372
                    theUseLabels = tags.getInt(DAL_USE_LABELS, USE_LABELS_NO);
1373
                } else {
1374
                    theUseLabels = USE_LABELS_NO;
1375
                }
1376
            }
1377
        } else {
1378
            theUseLabels = useLabels;
1379
        }
1380
        switch (theUseLabels) {
1381
            case USE_LABELS_YES:
1382
                if (StringUtils.isBlank(tableName)) {
1383
                    theLabel = attrdesc.getLocalizedLabel();
1384
                } else {
1385
                    theLabel = String.format("%s [%s]", attrdesc.getLocalizedLabel(), tableName);
1386
                }
1387
                break;
1388
            default:
1389
            case USE_LABELS_NO:
1390
                if (StringUtils.isBlank(tableName)) {
1391
                    theLabel = attrdesc.getName();
1392
                } else {
1393
                    theLabel = String.format("%s [%s]", attrdesc.getName(), tableName);
1394
                }
1395
                break;
1396
            case USE_LABELS_BOTH:
1397
                if (StringUtils.isBlank(tableName)) {
1398
                    theLabel = String.format("%s [%s]", attrdesc.getLocalizedLabel(), attrdesc.getName());
1399
                } else {
1400
                    theLabel = String.format("%s [%s/%s]", attrdesc.getLocalizedLabel(), attrdesc.getName(), tableName);
1401
                }
1402
                break;
1403
        }
1404
        return theLabel;
1405
    }
1406

    
1407
    private void doCalculatedColumns() {
1408
        WindowManager_v2 winmanager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
1409
        I18nManager i18n = ToolsLocator.getI18nManager();
1410
        final FeatureQueryCalculatedColumnsPanel panel = new DefaultFeatureQueryCalculatedColumnsPanel();
1411
        panel.setStore(this.store);
1412
        panel.put(this.parameters.getQuery());
1413
        final Dialog dialog = winmanager.createDialog(
1414
                panel.asJComponent(),
1415
                i18n.getTranslation("_Calculated_columns"),
1416
                null,
1417
                WindowManager_v2.BUTTONS_OK_CANCEL
1418
        );
1419
        dialog.addActionListener((ActionEvent e) -> {
1420
            if (dialog.getAction() == WindowManager_v2.BUTTONS_OK) {
1421
                panel.fetch(this.parameters.getQuery());
1422
                search();
1423
            }
1424
        });
1425
        dialog.show(WindowManager.MODE.DIALOG);
1426
    }
1427

    
1428
    private void doGroupBy() {
1429
        DataStoreProviderFactory dataFactory = this.store.getProviderFactory();
1430
        int allowGroupBy = ((FeatureStoreProviderFactory) dataFactory).allowGroupBy();
1431
        if (allowGroupBy != DataType.YES) {
1432
            // FIXME: mensaje al usaurio.
1433
            I18nManager i18n = ToolsLocator.getI18nManager();
1434
            ThreadSafeDialogsManager dialogs = ToolsSwingLocator.getThreadSafeDialogsManager();
1435
            dialogs.messageDialog(
1436
                    i18n.getTranslation("_The_group_function_is_not_available_for_this_table"),
1437
                    i18n.getTranslation("_Information"),
1438
                    JOptionPane.INFORMATION_MESSAGE
1439
            );
1440
            return;
1441
        }
1442

    
1443
        WindowManager_v2 winmanager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
1444
        I18nManager i18n = ToolsLocator.getI18nManager();
1445
        final FeatureQueryGroupByPanel panelGroupBy = new DefaultFeatureQueryGroupByPanel();
1446
        panelGroupBy.setStore(this.store);
1447
        panelGroupBy.put(this.parameters.getQuery());
1448
        final Dialog dialog = winmanager.createDialog(
1449
                panelGroupBy.asJComponent(),
1450
                i18n.getTranslation("_Select_group_columns_and_aggregate_functions"),
1451
                null,
1452
                WindowManager_v2.BUTTONS_OK_CANCEL
1453
        );
1454
        dialog.addActionListener((ActionEvent e) -> {
1455
            if (dialog.getAction() == WindowManager_v2.BUTTONS_OK) {
1456
                panelGroupBy.fetch(this.parameters.getQuery());
1457
                search();
1458
            }
1459
        });
1460
        dialog.show(WindowManager.MODE.DIALOG);
1461
    }
1462

    
1463
    private void doSelectResultColumnNames() {
1464
        WindowManager_v2 winmanager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
1465
        I18nManager i18n = ToolsLocator.getI18nManager();
1466
        final FeatureAttributesSelectionPanel panelSelectColumns = DALSwingLocator.getManager().createFeatureAttributeSelectionPanel();
1467
        panelSelectColumns.allowCalculatedAttributes(false);
1468
        FeatureType ftype = this.getFeatureType();
1469
        try {
1470
            Feature f = store.findFirst(this.parameters.getQuery());
1471
            if (f != null) {
1472
                ftype = f.getType();
1473
            }
1474
        } catch (Throwable ex) {
1475
            LOGGER.warn("Can't retrieve the feature type from the first feature.", ex);
1476
        }
1477
        panelSelectColumns.setFeatureType(ftype);
1478
        panelSelectColumns.setSelectedNames(this.parameters.getResultColumnNames());
1479
        final Dialog dialog = winmanager.createDialog(
1480
                panelSelectColumns.asJComponent(),
1481
                i18n.getTranslation("_Select_the_columns_to_display"),
1482
                null,
1483
                WindowManager_v2.BUTTONS_OK_CANCEL
1484
        );
1485
        dialog.addActionListener((ActionEvent e) -> {
1486
            if (dialog.getAction() == WindowManager_v2.BUTTONS_OK) {
1487
                this.setResultColumnNames(panelSelectColumns.getSelectedNames());
1488
                search();
1489
            }
1490
        });
1491
        dialog.show(WindowManager.MODE.DIALOG);
1492
    }
1493

    
1494
    @Override
1495
    public void put(SearchParameters inParams) {
1496
        this.parameters = (DefaultSearchParameters) inParams;
1497
        for (SearchConditionPanel conditionPanel : this.conditionPanels) {
1498
            try {
1499
                conditionPanel.put(inParams);
1500
            } catch (Exception ex) {
1501
                LOGGER.warn("Can't open panel", ex);
1502
            }
1503
        }
1504
        this.tabSearchMode.setSelectedIndex(inParams.getSearchMode());
1505
//        this.resetTable();
1506

    
1507
    }
1508

    
1509
    private FeatureQuery getQuery() {
1510
        FeatureQuery query;
1511
        try {
1512
            int searchMode = this.tabSearchMode.getSelectedIndex();
1513
            SearchConditionPanel panel = this.conditionPanels.get(searchMode);
1514
            Expression filter = panel.get();
1515
            if (searchMode != PANEL_ADVANCED) {
1516
                this.conditionPanels.get(PANEL_ADVANCED).set(filter);
1517
            }
1518
            query = (FeatureQuery) this.parameters.getQuery().clone();
1519
            query.retrievesAllAttributes();
1520
            if (ExpressionUtils.isPhraseEmpty(filter)) {
1521
                return query;
1522
            }
1523
            query.setFilter(filter);
1524
            query.retrievesAllAttributes();
1525
            return query;
1526
        } catch (Exception ex) {
1527
            LOGGER.warn("Can't build query.", ex);
1528
            return null;
1529
        }
1530
    }
1531

    
1532
    @Override
1533
    public SearchParameters fetch(SearchParameters outParams) {
1534
        // Actualiza el fquery del parameters con los paneles
1535
        for (SearchConditionPanel conditionPanel : conditionPanels) {
1536
            try {
1537
                conditionPanel.fetch(this.parameters);
1538
            } catch (Exception ex) {
1539
                LOGGER.warn("Panel not able to fetch values", ex);
1540
            }
1541
        }
1542

    
1543
        // Actualiza el filtro con el panel activo
1544
        int searchMode = this.tabSearchMode.getSelectedIndex();
1545
        SearchConditionPanel panel = this.conditionPanels.get(searchMode);
1546
        Expression filter = panel.get();
1547
        if (searchMode != PANEL_ADVANCED) {
1548
            this.conditionPanels.get(PANEL_ADVANCED).set(filter);
1549
        }
1550
        this.parameters.setSearchMode(searchMode);
1551
        FeatureQuery query = (FeatureQuery) this.parameters.getQuery();
1552
        this.lastQuery = query.getCopy();
1553
        query.retrievesAllAttributes();
1554
        query.clearFilter();
1555
        if (!ExpressionUtils.isPhraseEmpty(filter)) {
1556
            query.setFilter(filter);
1557
            query.retrievesAllAttributes();
1558
        }
1559

    
1560
        if (outParams == null) {
1561
            return this.parameters.getCopy();
1562
        }
1563
        outParams.copyFrom(this.parameters.getCopy());
1564
        return outParams;
1565
    }
1566

    
1567
    public static void selfRegister() {
1568
        String[][] iconNames = new String[][]{
1569
            new String[]{"dalswing", "featurestore-column"},
1570
            new String[]{"dalswing", "featurestore-foreing-key"},
1571
            new String[]{"dalswing", "featurestore-table"},
1572
            new String[]{"dalswing", "search-action-select"},
1573
            new String[]{"dalswing", "search-action-select-add"},
1574
            new String[]{"dalswing", "search-action-select-filter"},        
1575
            new String[]{"dalswing", "search-nullbehavior-null"},
1576
            new String[]{"dalswing", "search-nullbehavior-true"},
1577
            new String[]{"dalswing", "search-nullbehavior-false2"}
1578
       
1579
        };
1580
        IconTheme theme = ToolsSwingLocator.getIconThemeManager().getCurrent();
1581
        for (String[] icon : iconNames) {
1582
            URL url = DefaultSearchPanel.class.getResource(icon[1] + ".png");
1583
            theme.registerDefault("DALSwing", icon[0], icon[1], null, url);
1584
        }
1585

    
1586
        ConfigurableActionsMamager cfgActionsManager = ToolsUtilLocator.getConfigurableActionsMamager();
1587
        cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new UseLabelsYesAction());
1588
        cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new UseLabelsNoAction());
1589
        cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new UseLabelsBothAction());
1590
        cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new SelectColumnsAction());
1591
        cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new CalculatedColumnsAction());
1592
        cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new GroupByAction());
1593
        cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new OrderByAction());
1594
    }
1595
    
1596
    private void doSelectSearchPostprocess() throws DataException {
1597
        DataSwingManager manager = DALSwingLocator.getDataSwingManager();
1598
        Map<String, SearchPostProcessFactory> searchPostProcessFactoryMap = manager.getSearchPostProcess();
1599

    
1600
        JPopupMenu menu = new JPopupMenu();
1601
        for (String factory : searchPostProcessFactoryMap.keySet()) {
1602
            JMenuItem item;
1603
            item = new JMenuItem(factory);
1604
            SearchParameters searchParams = this.fetch(this.parameters.getCopy());
1605
            FeatureQuery myQuery = searchParams.getQuery().getCopy();
1606
//            item.addActionListener(new SearchPostProcessListener(this.store, myQuery, manager.getSearchPostProcess(factory)));
1607
            item.addActionListener((ActionEvent e) -> {
1608
                doSearchPostProcess(store, myQuery, manager.getSearchPostProcess(factory), searchParams );
1609
            });
1610
            menu.add(item);
1611
        }
1612
        menu.show(this.btnSearchPostProcess, 0, this.btnSearchPostProcess.getHeight());
1613
    }
1614

    
1615
    private void doExecuteSearchPostProcess(
1616
            FeatureStore input,
1617
            FeatureQuery query,
1618
            SearchPostProcessFactory factory,
1619
            DynObject parameters
1620
            ) {
1621
                Cursor savedCursor = this.getCursor();
1622
                SimpleTaskStatus status = ToolsLocator.getTaskStatusManager().createDefaultSimpleTaskStatus("");
1623
        status.setAutoremove(true);
1624
        status.add();
1625
        this.taskStatusController.bind(status);
1626
        Thread task = new Thread(() -> {
1627
            try {
1628
                                SwingUtilities.invokeLater(() -> {this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));});
1629
                this.processing = true;
1630
                this.updateComponentState();                                
1631
                SearchPostProcess process = factory.createProcess(factory, input, query, parameters);
1632

    
1633
                if (parameters != null) {
1634
                    process.setParameters(parameters);
1635
                }
1636
                //Ejecutar el execute en thread para no bloquear el software
1637
                SearchPostProcess.SearchPostProcessResult output = process.execute(input, query, parameters, status);
1638
                                if (output != null) {
1639
                                        this.postProcessStore = output.getStore();
1640
                                        this.postProcessQuery = output.getQuery();
1641

    
1642
                                        doLoadSearchPostProccessResults(this.postProcessStore);
1643

    
1644
                                }
1645
                this.currentPostProcess = factory.getName();
1646
                                status.terminate();
1647
                                
1648
            }catch (Exception ex){
1649
                LOGGER.warn("SearchPostProcess not able to be executed.", ex);
1650
                resetPostProcessTable();
1651
                                status.setTitle(ToolsLocator.getI18nManager().getTranslation("_Error_in_post_process_operation"));
1652
                                status.message("");
1653
                                status.abort();
1654
            } finally {
1655
                                SwingUtilities.invokeLater(() -> {this.setCursor(savedCursor);});
1656
                this.processing = false;
1657
                this.updateComponentState();
1658
            }
1659
        }, "ExecuteSearchPostProcess");
1660

    
1661
        task.start();
1662

    
1663
    }
1664

    
1665
    private void doLoadSearchPostProccessResults(FeatureStore input) {
1666
                if (!SwingUtilities.isEventDispatchThread()) {
1667
            SwingUtilities.invokeLater(() -> {
1668
                                doLoadSearchPostProccessResults(input);
1669
                        });
1670
            return;
1671
        }
1672

    
1673
        final List<Feature> featuresSearchPostProccessResults;
1674
        final FeatureQuery finalQuery;
1675
        finalQuery = null;
1676
        try {  
1677
            this.tabResults.setEnabledAt(1, true);
1678
            this.tabResults.setSelectedIndex(1);
1679
            featuresSearchPostProccessResults = input.getFeatures(finalQuery, 20);
1680
            FacadeOfAFeaturePagingHelper facadeSearchPostProccessResults = (FacadeOfAFeaturePagingHelper) featuresSearchPostProccessResults;
1681
            FeatureType ftypeSearchPostProccessResults = facadeSearchPostProccessResults.getFeaturePagingHelper().getFeatureSet().getDefaultFeatureType();
1682
            // al modelo le pasamos el ftype de esas features
1683
            resultPostProcessModel = new SimpleFeaturesTableModelImpl(
1684
                    ftypeSearchPostProccessResults,
1685
                    this.parameters.getResultColumnNames(),
1686
                    featuresSearchPostProccessResults
1687
            );
1688

    
1689
            I18nManager i18n = ToolsLocator.getI18nManager();
1690
            TableModel oldmodel = tblSearchPostProcessResults.getModel();
1691
            tblSearchPostProcessResults.setModel(resultPostProcessModel);
1692
            resultPostProcessModel.setCellRenderers(tblSearchPostProcessResults);
1693
            if (oldmodel instanceof SimpleFeaturesTableModel) {
1694
                ((SimpleFeaturesTableModel) oldmodel).dispose();
1695
            }
1696
            updateNumberElementsMsg(resultPostProcessModel);
1697
//            if (resultPostProcessModel.hasErrors()) {
1698
//                lblMsg.setText("_Errors_occurred_load_search_post_process");
1699
//            } else {
1700
//                lblMsg.setText(String.format("%d " + i18n.getTranslation("_elements"), resultPostProcessModel.getRowCount()));
1701
//            }
1702
        } catch (Exception ex) {
1703
            resetPostProcessTable();
1704
            LOGGER.warn("SearchPostProcess not able to be executed. Can't get features or create table model", ex);
1705
        }
1706
    }
1707

    
1708
    private void updateComponentState() {
1709
        if (!SwingUtilities.isEventDispatchThread()) {
1710
            SwingUtilities.invokeLater(this::updateComponentState);
1711
            return;
1712
        }
1713
        this.pgbStatus.setVisible(processing);
1714
        this.setEnabled(!processing);
1715
    }
1716
    
1717
    private void resetPostProcessTable() {
1718
        if(!SwingUtilities.isEventDispatchThread()) {
1719
            SwingUtilities.invokeLater(this::resetPostProcessTable);
1720
            return;
1721
        }
1722
       
1723
        this.tblSearchPostProcessResults.setModel(new DefaultTableModel());
1724
    }
1725
    
1726
    private void doSearchPostProcess(FeatureStore store, FeatureQuery query, SearchPostProcessFactory factory, SearchParameters searchParams){
1727
        if (factory.hasProcessParameters()) {
1728
                DynObject parametersPostProcess = factory.createProcessParameters(store, query, searchParams);
1729
                JDynForm form = DynFormLocator.getDynFormManager().createJDynForm(parametersPostProcess);
1730
                form.setLayoutMode(JDynForm.USE_SEPARATORS);
1731

    
1732
                I18nManager i18n = ToolsLocator.getI18nManager();
1733
                WindowManager_v2 windowManager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
1734

    
1735
                Dialog dialog = windowManager.createDialog(
1736
                        form.asJComponent(),
1737
                        i18n.getTranslation("_Postprocess_parameters"),
1738
                        i18n.getTranslation(
1739
                                "_Parameters_for_XpostprocessNameX_postprocess_on_XtableNameX",
1740
                                new String[] {
1741
                                    factory.getName(),
1742
                                    this.store.getName()
1743
                                }
1744
                        ),
1745
                        WindowManager_v2.BUTTONS_OK_CANCEL);
1746
                
1747
                ToolsSwingUtils.ensureRowsCols(dialog.asJComponent(), 20, 60, 30,100);
1748
                dialog.addActionListener((ActionEvent e2) -> {
1749
                    if (dialog.getAction() == WindowManager_v2.BUTTON_OK) {
1750
                        form.getValues(parametersPostProcess); // actualiza el valor de lo los parametros con los valores introducidos por el usuario
1751
                        doExecuteSearchPostProcess(store, query, factory, parametersPostProcess);
1752
                        this.postProcessParams = parametersPostProcess;
1753
                    }
1754
                });
1755

    
1756
                dialog.show(WindowManager.MODE.DIALOG);
1757

    
1758
            } else {
1759
                doExecuteSearchPostProcess(store, query, factory, null);
1760
            }
1761
    }
1762
    
1763
    private void updateNumberElementsMsg( SimpleFeaturesTableModel model){
1764
        I18nManager i18n = ToolsLocator.getI18nManager();
1765
        
1766
        if (model.hasErrors()) {
1767
            this.taskStatusController.setTitle(i18n.getTranslation("_Errors_occurred_load_search_post_process"));
1768
        } else {
1769
            this.taskStatusController.setTitle(String.format("%d " + i18n.getTranslation("_elements"), model.getRowCount()));
1770
        }
1771
    }
1772
    
1773
    @Override
1774
    public boolean isVisible(Object component) {
1775
       if( this.filterOnlyMode ) {
1776
            if( component instanceof GroupByAction ) {
1777
                return false;
1778
            }
1779
//            if( component instanceof OrderByAction ) {
1780
//                return false;
1781
//            }
1782
//            if( component instanceof CalculatedColumnsAction ) {
1783
//                return false;
1784
//            }
1785
        }
1786
        return true;
1787
    }
1788

    
1789
    @Override
1790
    public boolean isEnabled(Object component) {
1791
        if( component instanceof GroupByAction ) {
1792
            DataStoreProviderFactory dataFactory = this.store.getProviderFactory();
1793
            int allowGroupBy = ((FeatureStoreProviderFactory) dataFactory).allowGroupBy();
1794
            if (allowGroupBy != DataType.YES) {
1795
                return false;
1796
            }
1797
        }
1798
        return true;
1799
    }
1800

    
1801
    @Override
1802
    public void setFilterOnlyMode(boolean filterOnlyMode) {
1803
        if( this.conditionPanels!=null ) {
1804
            throw new IllegalStateException("Cannot change filter-only-mode after invoking asJComponent.");
1805
        }
1806
        this.filterOnlyMode = filterOnlyMode;
1807
        this.showActions = false;
1808
    }
1809

    
1810
    @Override
1811
    public boolean isFilterOnlyMode() {
1812
        return this.filterOnlyMode;
1813
    }
1814

    
1815
    @Override
1816
    public Feature getLastSelectedFeature() {
1817
        return this.lastSelectedFeature;
1818
    }
1819

    
1820
    @Override
1821
    public Object getProperty(String name) {
1822
        return this.propertiesHelper.getProperty(name);
1823
    }
1824

    
1825
    @Override
1826
    public void setProperty(String name, Object value) {
1827
        this.propertiesHelper.setProperty(name, value);
1828
    }
1829

    
1830
    @Override
1831
    public Map<String, Object> getProperties() {
1832
        return this.propertiesHelper.getProperties();
1833
    }
1834

    
1835
  
1836
}
1837