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

History | View | Annotate | Download (62.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.locator.ReferenceNotRegisteredException;
108
import org.gvsig.tools.swing.api.SupportIsEnable;
109
import org.gvsig.tools.swing.api.SupportIsVisible;
110
import org.gvsig.tools.swing.api.ToolsSwingUtils;
111
import org.gvsig.tools.swing.api.bookmarkshistory.ActionEventWithCurrentValue;
112
import static org.gvsig.tools.swing.api.bookmarkshistory.ActionEventWithCurrentValue.ID_GETVALUE;
113
import static org.gvsig.tools.swing.api.bookmarkshistory.ActionEventWithCurrentValue.ID_SETVALUE;
114
import org.gvsig.tools.swing.api.bookmarkshistory.BookmarksController;
115
import org.gvsig.tools.swing.api.bookmarkshistory.BookmarksController.BookmarkEvent;
116
import org.gvsig.tools.swing.api.bookmarkshistory.HistoryController;
117
import org.gvsig.tools.swing.api.task.TaskStatusController;
118
import org.gvsig.tools.swing.api.threadsafedialogs.ThreadSafeDialogsManager;
119
import org.gvsig.tools.task.SimpleTaskStatus;
120
import org.gvsig.tools.util.PropertiesSupportHelper;
121

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

    
131
        private static final Logger LOGGER = LoggerFactory.getLogger(DefaultSearchPanel.class);
132

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

    
141
        public static class UseLabelsYesAction extends AbstractAction {
142

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

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

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

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

    
167
        public static class UseLabelsNoAction extends AbstractAction {
168

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

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

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

    
192
        public static class UseLabelsBothAction extends AbstractAction {
193

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

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

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

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

    
218
        public static class SelectColumnsAction extends AbstractAction {
219

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

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

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

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

    
245
        public static class CalculatedColumnsAction extends AbstractAction {
246

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

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

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

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

    
272
        public static class GroupByAction extends AbstractAction {
273

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

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

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

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

    
299
        public static class OrderByAction extends AbstractAction {
300

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

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

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

    
319
                @Override
320
                public void actionPerformed(ActionEvent ae) {
321
                        DefaultSearchPanel panel = (DefaultSearchPanel) ae.getSource();
322
                        panel.doOrderBy();
323
                }
324
        }
325

    
326
        private class TablePopupMenu extends JPopupMenu {
327

    
328
                public final JTable table;
329

    
330
                @SuppressWarnings("OverridableMethodCallInConstructor")
331
                public TablePopupMenu(JTable inputTable) {
332
                        this.table = inputTable;
333
                        I18nManager i18n = ToolsLocator.getI18nManager();
334
                        JMenuItem copyRowsActionMenu = new JMenuItem(i18n.getTranslation("_Copy_rows"));
335
                        copyRowsActionMenu.addActionListener((ActionEvent e) -> {
336
                                doCopyRows(table);
337
                        });
338
                        this.add(copyRowsActionMenu);
339
                }
340
        }
341

    
342
        private class ActionButtons {
343

    
344
                private final DALActionFactory factory;
345
                private final Action action;
346
                private final JButton button;
347

    
348
                public ActionButtons(DALActionFactory factory, Action action, JButton button) {
349
                        this.factory = factory;
350
                        this.action = action;
351
                        this.button = button;
352
                }
353
        }
354

    
355
        public static class SearchActionContext extends AbstractDALActionContext {
356

    
357
                private final DefaultSearchPanel panel;
358

    
359
                public SearchActionContext(DefaultSearchPanel panel) {
360
                        super(FeatureStoreSearchPanel.ACTION_CONTEXT_NAME);
361
                        this.panel = panel;
362
                }
363

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

    
382
                @Override
383
                public JComponent getActionButton(String actionName) {
384
                        return this.panel.getActionButton(actionName);
385
                }
386

    
387
                @Override
388
                public int getSelectedsCount() {
389
                        return this.panel.getSelectedFeatureCount();
390
                }
391

    
392
                @Override
393
                public Expression getFilterForSelecteds() {
394
                        return this.panel.getFilterForSelectedFeature();
395
                }
396

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

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

    
470
        private List<SearchConditionPanel> conditionPanels;
471

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

    
479
        private String currentPostProcess;
480

    
481
        private DynObject postProcessParams;
482
        private FeatureStore postProcessStore;
483
        private FeatureQuery postProcessQuery;
484
        private SimpleFeaturesTableModel resultModel;
485
        private SimpleFeaturesTableModel resultPostProcessModel;
486

    
487
        private boolean processing;
488
        private JComponent configurableActions;
489

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

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

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

    
538
        @Override
539
        public JComponent asJComponent() {
540
                if (this.conditionPanels == null) {
541
                        this.initComponents();
542
                }
543
                return this;
544
        }
545

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

    
572
        @Override
573
        public void addActionListener(ActionListener listener) {
574
                this.acctionListeners.addActionListener(listener);
575
        }
576

    
577
        @Override
578
        public ActionListener[] getActionListeners() {
579
                return this.acctionListeners.getActionListeners();
580
        }
581

    
582
        @Override
583
        public void removeActionListener(ActionListener listener) {
584
                this.acctionListeners.removeActionListener(listener);
585
        }
586

    
587
        @Override
588
        public void removeAllActionListener() {
589
                this.acctionListeners.removeAllActionListener();
590
        }
591

    
592
        @Override
593
        public void fireActionEvent(ActionEvent event) {
594
                this.acctionListeners.fireActionEvent(event);
595
        }
596

    
597
        @Override
598
        public boolean hasActionListeners() {
599
                return this.acctionListeners.hasActionListeners();
600
        }
601

    
602
        private void initComponents() {
603
                this.conditionPanels = new ArrayList<>();
604

    
605
                ToolsSwingManager swingManager = ToolsSwingLocator.getToolsSwingManager();
606
                swingManager.translate(this.tabSearchMode);
607
                swingManager.translate(this.tabResults);
608
                swingManager.translate(this.btnSearch);
609
                swingManager.translate(this.btnClear);
610
                swingManager.translate(this.btnSearchPostProcess);
611
                swingManager.translate(this.lblExpressionDeBusqueda);
612
                swingManager.translate(this.btnAddAccumulatedFilter);
613
                swingManager.translate(this.btnRemoveAccumulatedFilter);
614
                swingManager.translate(this.btnViewAccumulatedFilter);
615

    
616
                ConfigurableActionsMamager cfgActionsManager = ToolsUtilLocator.getConfigurableActionsMamager();
617
                this.configurableActions = cfgActionsManager.getConfigurableActionsComponent(CONFIGURABLE_PANEL_ID, this);
618
                this.pnlCfgActions.setLayout(new BorderLayout(0, 0));
619
                this.pnlCfgActions.add(configurableActions, BorderLayout.CENTER);
620

    
621
                this.taskStatusController = ToolsSwingLocator.getTaskStatusSwingManager().createTaskStatusController(
622
                        this.lblStatusTitle,
623
                        this.lblMsg,
624
                        this.pgbStatus);
625
                this.pgbStatus.setVisible(false);
626

    
627
                this.conditionPanels.add(
628
                        new SearchConditionPanelSimplified(
629
                                parameters,
630
                                store,
631
                                btnAddAccumulatedFilter,
632
                                btnRemoveAccumulatedFilter,
633
                                btnViewAccumulatedFilter,
634
                                lblField1,
635
                                lblExtraFields1,
636
                                lblRelationalOperator1,
637
                                cboValue1,
638
                                lblNull1,
639
                                lblLogicalOperators1,
640
                                lblField2,
641
                                lblExtraFields2,
642
                                lblRelationalOperator2,
643
                                cboValue2,
644
                                lblNull2,
645
                                lblLogicalOperators2,
646
                                lblField3,
647
                                lblExtraFields3,
648
                                lblRelationalOperator3,
649
                                cboValue3,
650
                                lblNull3,
651
                                lblLogicalOperators3,
652
                                lblField4,
653
                                lblExtraFields4,
654
                                lblRelationalOperator4,
655
                                cboValue4,
656
                                lblNull4,
657
                                null
658
                        )
659
                );
660

    
661
                SearchConditionPanelAdvanced advancedPanel = new SearchConditionPanelAdvanced(
662
                        this.store,
663
                        txtAdvancedExpression,
664
                        btnAdvancedExpression,
665
                        btnAdvancedExpressionHistory,
666
                        btnAdvancedExpressionBookmarks
667
                );
668
                this.conditionPanels.add(advancedPanel);
669

    
670
                for (SearchConditionPanelFactory factory : DALSwingLocator.getManager().getSearchConditionPanels()) {
671
                        String factoryName = "unknown";
672
                        try {
673
                                factoryName = factory.getName();
674
                                if (factory.isApplicable(store)) {
675
                                        SearchConditionPanel panel = factory.create(this);
676
                                        this.conditionPanels.add(panel);
677
                                        this.tabSearchMode.add(factory.getName(), panel.asJComponent());
678
                                }
679
                        } catch (Throwable th) {
680
                                LOGGER.warn("Can't create search panel '" + factoryName + "'.");
681
                        }
682
                }
683

    
684
                this.btnSearch.addActionListener((ActionEvent e) -> {
685
                        this.tabResults.setEnabledAt(1, false);
686
                        search();
687
                });
688

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

    
706
                //swingManager.createTableColumnAdjuster(tblResults);
707
                //swingManager.createTableColumnAdjuster(tblSearchPostProcessResults);
708
//        this.setPreferredSize(new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT));
709
                ToolsSwingUtils.ensureRowsCols(this, 20, 100, 30, 120);
710

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

    
714
                this.historyController.setFilter(null);
715

    
716
                this.historyController.addActionListener((ActionEvent e) -> {
717
                        ActionEventWithCurrentValue<DefaultSearchParameters> b = (ActionEventWithCurrentValue<DefaultSearchParameters>) e;
718
                        switch (b.getID()) {
719
                                case ID_GETVALUE:
720
                                        DefaultSearchParameters actualParams = (DefaultSearchParameters) fetch(null);
721
                                        b.setCurrentValue(actualParams);
722
                                        break;
723

    
724
                                case ID_SETVALUE:
725
                                        if (b.getCurrentValue() == null) {
726
                                                return;
727
                                        }
728
                                        doSearchFromParameters(b.getCurrentValue());
729
                                        break;
730
                        }
731
                });
732
                this.bookmarksController.addActionListener((ActionEvent e) -> {
733
                        BookmarkEvent<DefaultSearchParameters> b = (BookmarkEvent<DefaultSearchParameters>) e;
734
                        switch (b.getID()) {
735
                                case ID_GETVALUE:
736
                                        DefaultSearchParameters actualParams = (DefaultSearchParameters) fetch(null);
737
                                        b.setCurrentValue(actualParams);
738
                                        break;
739

    
740
                                case ID_SETVALUE:
741
                                        if (b.getCurrentValue() == null) {
742
                                                return;
743
                                        }
744
                                        b.getBookmark().used();
745
                                        doSearchFromParameters(b.getCurrentValue());
746
                                        break;
747
                        }
748
                });
749
                this.addComponentListener(new ComponentAdapter() {
750
                        @Override
751
                        public void componentHidden(ComponentEvent e) {
752
                                dispose();
753
                        }
754
                });
755

    
756
                this.btnSearchPostProcess.addActionListener((ActionEvent e) -> {
757
                        try {
758
                                doSelectSearchPostprocess();
759
                        } catch (DataException ex) {
760
                                LOGGER.warn("Can't select a Search Post Process", ex);
761
                        }
762
                });
763

    
764
                this.tabResults.setEnabledAt(1, false);
765

    
766
                this.tblResults.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
767
                this.tblResults.addKeyListener(new KeyAdapter() {
768
                        @Override
769
                        public void keyPressed(KeyEvent e) {
770
                                if (e.getKeyCode() == KeyEvent.VK_F4) {
771
                                        doShowCellInDialog();
772
                                }
773
                        }
774
                });
775

    
776
                this.tblResults.setComponentPopupMenu(new TablePopupMenu(this.tblResults));
777
                this.tblSearchPostProcessResults.setComponentPopupMenu(new TablePopupMenu(this.tblSearchPostProcessResults));
778

    
779
                this.tabResults.addChangeListener((ChangeEvent evt) -> {
780
                        SwingUtilities.invokeLater(() -> {
781
                                if (tabResults.getSelectedIndex() == 0) {
782
                                        updateNumberElementsMsg(resultModel);
783
                                } else {
784
                                        updateNumberElementsMsg(resultPostProcessModel);
785
                                }
786
                        });
787
                });
788
                if (this.filterOnlyMode) {
789
                        this.btnSearchPostProcess.setVisible(false);
790
                }
791

    
792
                //this.tblResults.add
793
                if (this.bookmarks.hasBookmark(this.store.getName())) {
794
                        Bookmark<DefaultSearchParameters> initBookmark = this.bookmarks.get(this.store.getName());
795
                        initBookmark.used();
796
                        doSearchFromParameters(initBookmark.getValue());
797
                } else {
798
                    clear();
799
                    search();
800
                }
801
        }
802
        
803
    private void doSearchFromParameters(DefaultSearchParameters searchParams) {
804
        DefaultSearchParameters params;
805
        try {
806
            params = searchParams.getCopy();
807
            params.fix(this.getFeatureType());
808
            // TODO: habria que comprobar y preguntar al usuario de forma
809
            // similar a lo que se hace en DefaultFeatureQueryCalculatedColumnsPanel.doRemove
810
        } catch (Exception ex) {
811
            LOGGER.warn("Not been able to clone export parameters", ex);
812
            return;
813
        }
814
        clear();
815
        put(params);
816
        Thread th = new Thread(() -> {
817
            doSearch(params);
818
        });
819
        th.start();
820

    
821
    }
822

    
823
        private void doShowCellInDialog() {
824
                int row = this.tblResults.getSelectedRow();
825
                if (row < 0) {
826
                        return;
827
                }
828
                int col = this.tblResults.getSelectedColumn();
829
                if (col < 0) {
830
                        return;
831
                }
832
                String s = Objects.toString(this.tblResults.getValueAt(row, col), null);
833
                if (StringUtils.isBlank(s)) {
834
                        return;
835
                }
836
                ToolsSwingLocator.getToolsSwingManager().showZoomDialog(
837
                        this,
838
                        this.tblResults.getColumnName(col),
839
                        s,
840
                        false
841
                );
842
        }
843

    
844
        @Override
845
        public FeatureType getFeatureType() {
846
                try {
847
                        return store.getDefaultFeatureType();
848
                } catch (Exception ex) {
849
                        throw new RuntimeException("Can't retrieve the feature type.", ex);
850
                }
851
        }
852

    
853
        @Override
854
        public void setEnabled(boolean enabled) {
855
                if (!SwingUtilities.isEventDispatchThread()) {
856
                        SwingUtilities.invokeLater(() -> {
857
                                setEnabled(enabled);
858
                        });
859
                        return;
860
                }
861

    
862
                if (this.conditionPanels == null) {
863
                        this.initComponents();
864
                }
865
                for (SearchConditionPanel conditionPanel : conditionPanels) {
866
                        conditionPanel.setEnabled(enabled);
867
                }
868

    
869
                this.btnClear.setEnabled(enabled);
870
                this.btnSearch.setEnabled(enabled);
871
                for (ActionButtons actionButton : actions.values()) {
872
                        actionButton.action.setEnabled(enabled);
873
                }
874
                this.btnSearchPostProcess.setEnabled(enabled);
875
                //bookmarkController,historyController,configurableActions
876
        }
877

    
878
        @Override
879
        public void clear() {
880
                this.taskStatusController.setTitle("");
881
                if (this.conditionPanels == null) {
882
                        return;
883
                }
884
                for (SearchConditionPanel conditionPanel : conditionPanels) {
885
                        conditionPanel.clear();
886
                }
887
                FeatureQuery emptyQuery = this.store.createFeatureQuery();
888
                emptyQuery.retrievesAllAttributes();
889
                this.parameters.setQuery(emptyQuery);
890
                // Mantener las columnas visualizadas
891
                // Elimina las que no existen en el store como campos calculados que
892
                // pudieran existir en el fquery
893
                List<String> resultColumnNames = this.parameters.getResultColumnNames();
894
                ArrayList<String> toDeleteAlreadyDontExist = new ArrayList<>();
895
                for (String resultColumnName : resultColumnNames) {
896
                        try {
897
                                FeatureAttributeDescriptor attr = this.store.getDefaultFeatureType().getAttributeDescriptor(resultColumnName);
898
                                if (attr == null) {
899
                                        toDeleteAlreadyDontExist.add(resultColumnName);
900
                                }
901
                        } catch (DataException ex) {
902

    
903
                        }
904
                }
905
                resultColumnNames.removeAll(toDeleteAlreadyDontExist);
906
                resetTable();
907
        }
908

    
909
        @Override
910
        public FeatureQuery getLastQuery() {
911
                return this.lastQuery;
912
        }
913

    
914
        public boolean isValid(StringBuilder message) {
915
                int searchMode = this.tabSearchMode.getSelectedIndex();
916
                SearchConditionPanel panel = this.conditionPanels.get(searchMode);
917
                boolean valid = panel.isValid(message);
918
                return valid;
919
        }
920

    
921
        @Override
922
        public void search() {
923
                StringBuilder message = new StringBuilder();
924
                if (!this.isValid(message)) {
925
                        ThreadSafeDialogsManager dialogManager = ToolsSwingLocator.getThreadSafeDialogsManager();
926
                        dialogManager.messageDialog(
927
                                "_The_specified_search_condition_is_not_valid",
928
                                "_Search",
929
                                JOptionPane.WARNING_MESSAGE
930
                        );
931
                        return;
932
                }
933
                lblMsg.setText(ToolsLocator.getI18nManager().getTranslation("_Searching") + "...");
934
                setEnabled(false);
935
                Thread th = new Thread(() -> {
936
                        try {
937
                                SearchParameters searchParams;
938
                                try {
939
                                        searchParams = this.fetch(this.parameters.getCopy()); // esto lo actualiza a la ultima // decidir si se devuelve clonado
940

    
941
                                        Date date = Calendar.getInstance().getTime();
942
                                        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
943
                                        String strDate = dateFormat.format(date);
944
                                        searchParams.setName("Params: " + strDate);
945
                                } catch (Exception ex) {
946
                                        LOGGER.warn("Not able to create search parameters.", ex);
947
                                        this.taskStatusController.setTitle(ToolsLocator.getI18nManager().getTranslation("_Errors_fetching_new_query") + "...");
948
                                        resetTable();
949
                                        return;
950
                                }
951
                                doSearch(searchParams);
952
                        } catch (Exception ex) {
953
                                LOGGER.warn("Search panel has errors during the search", ex);
954
                                resetTable();
955
                        } finally {
956
                                SwingUtilities.invokeLater(() -> {
957
                                        setEnabled(true);
958
                                });
959
                        }
960
                });
961
                th.start();
962
        }
963

    
964
        private void doSearch(SearchParameters searchParams) {
965
                final MutableObject model = new MutableObject(null);
966
                final MutableLong rowCount = new MutableLong();
967
                Cursor savedCursor = this.getCursor();
968
                SimpleTaskStatus status = ToolsLocator.getTaskStatusManager().createDefaultSimpleTaskStatus("");
969
                status.setAutoremove(true);
970
                status.add();
971
                this.taskStatusController.bind(status);
972
                try {
973
                        status.setTitle(ToolsLocator.getI18nManager().getTranslation("_Processing_search"));
974
                        SwingUtilities.invokeLater(() -> {
975
                                this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
976
                        });
977
                        final List<Feature> features;
978
                        FeatureQuery myQuery;
979
//                myQuery = this.getQuery().getCopy();
980
                        this.tabResults.setSelectedIndex(0);
981
                        List<String> resultColumnNames = searchParams.getResultColumnNames();
982
                        myQuery = searchParams.getQuery().getCopy();
983
                        features = store.getFeatures(myQuery, 50);
984
                        FacadeOfAFeaturePagingHelper facade = (FacadeOfAFeaturePagingHelper) features;
985
                        FeatureType ftype = facade.getFeaturePagingHelper().getFeatureSet().getDefaultFeatureType();
986
                        // al modelo le pasamos el ftype de esas features
987
                        SimpleFeaturesTableModel tableModel = new SimpleFeaturesTableModelImpl(
988
                                ftype,
989
                                resultColumnNames,
990
                                features
991
                        );
992
                        model.setValue(tableModel);
993
                        rowCount.setValue(tableModel.getRowCount());
994
                } catch (Exception ex) {
995
                        LOGGER.warn("Search not able to be executed. Can't get features or create table model", ex);
996
                        status.setTitle(ToolsLocator.getI18nManager().getTranslation("_Errors_getting_new_feature_set") + "...");
997
                        status.abort();
998
                        resetTable();
999
                } finally {
1000
                        SwingUtilities.invokeLater(() -> {
1001
                                I18nManager i18n = ToolsLocator.getI18nManager();
1002
                                try {
1003
                                        TableModel oldmodel = tblResults.getModel();
1004
                                        resultModel = (SimpleFeaturesTableModel) model.getValue();
1005
                                        tblResults.setModel(resultModel);
1006
                                        resultModel.setCellRenderers(tblResults, getCustomRenderers(searchParams));
1007
                                        if (oldmodel instanceof SimpleFeaturesTableModelImpl) {
1008
                                                ((SimpleFeaturesTableModelImpl) oldmodel).dispose();
1009
                                        }
1010
                                        if (resultModel.hasErrors()) {
1011
                                                status.setTitle(i18n.getTranslation("_Errors_occurred_during_search"));
1012
                                        } else {
1013
                                                status.setTitle(String.format("%d " + i18n.getTranslation("_elements"), rowCount.getValue()));
1014
                                        }
1015
                                        if (this.parameters != null && this.parameters.getQuery() != null) {
1016
                                                this.history.add(searchParams);
1017
                                        }
1018
                                } catch (Exception ex) {
1019
                                        LOGGER.warn(" Errors occurred during search getting old model", ex);
1020
                                        status.setTitle(i18n.getTranslation("_Errors_occurred_during_search"));
1021
                                } finally {
1022
                                        setEnabled(true);
1023
                                        status.terminate();
1024
                                        this.setCursor(savedCursor);
1025
                                }
1026
                        });
1027
                }
1028
        }
1029

    
1030
        private Map<String, TableCellRenderer> getCustomRenderers(SearchParameters parameters) {
1031
                FeatureType ft = this.store.getDefaultFeatureTypeQuietly();
1032
                HashMap<String, TableCellRenderer> renderers = new HashMap<String, TableCellRenderer>();
1033
                for (FeatureAttributeDescriptor attr : ft) {
1034
                        if (attr.getDataType().isNumeric()) {
1035
//                renderers.put(attr.getName(), new ColorRangeRenderer(attr, 20, 50));
1036
                        }
1037
                }
1038
                return renderers;
1039
        }
1040

    
1041
        private void resetTable() {
1042
                if (!SwingUtilities.isEventDispatchThread()) {
1043
                        SwingUtilities.invokeLater(this::resetTable);
1044
                        return;
1045
                }
1046
                List<String> resultColumnNames = null;
1047
                try {
1048
                        resultColumnNames = this.parameters.getResultColumnNames();
1049
                } catch (Exception ex) {
1050

    
1051
                }
1052
                FeatureType ftype = this.store.getDefaultFeatureTypeQuietly();
1053
                SimpleFeaturesTableModelImpl emptyTableModel = new SimpleFeaturesTableModelImpl(
1054
                        ftype,
1055
                        resultColumnNames,
1056
                        null
1057
                );
1058
                this.tblResults.setModel(emptyTableModel);
1059

    
1060
        }
1061

    
1062
        public void setResultColumnNames(List<String> names) {
1063
                this.parameters.getResultColumnNames().clear();
1064
                this.parameters.getResultColumnNames().addAll(names);
1065
//        if (this.conditionPanels == null) {
1066
//            return;
1067
//        }
1068
//        SimpleFeaturesTableModelImpl model;
1069
////        model = (SimpleFeaturesTableModel) this.tblResults.getModel();
1070
//        List<Feature> features = store.getFeatures(this.parameters.getQuery());
1071
//        FacadeOfAFeaturePagingHelper facade = (FacadeOfAFeaturePagingHelper) features;
1072
//        FeatureType ftype = facade.getFeaturePagingHelper().getFeatureSet().getDefaultFeatureType();
1073
//        model = new SimpleFeaturesTableModelImpl(
1074
//                ftype,
1075
//                this.parameters.getResultColumnNames(),
1076
//                features
1077
//        );
1078
//        tblResults.setModel(model);
1079
        }
1080

    
1081
        @Override
1082
        public boolean setFilter(Expression filter) {
1083
                try {
1084
                        if (this.conditionPanels == null) {
1085
                                this.initComponents();
1086
                        }
1087
                        if (ExpressionUtils.isPhraseEmpty(filter)) {
1088
                                this.clear();
1089
                                return true;
1090
                        }
1091
                        int panel = 0;
1092
                        int selected = PANEL_ADVANCED;
1093
                        for (SearchConditionPanel conditionPanel : conditionPanels) {
1094
                                if (panel != PANEL_ADVANCED && conditionPanel.set(filter)) {
1095
                                        selected = panel;
1096
                                }
1097
                                panel++;
1098
                        }
1099
                        this.tabSearchMode.setSelectedIndex(selected);
1100

    
1101
//            SimpleFeaturesTableModel model = new SimpleFeaturesTableModel(this.getStore());
1102
//            tblResults.setModel(model);
1103
//            lblMsg.setText("");
1104
                        return true;
1105
                } catch (Exception ex) {
1106
                        LOGGER.warn("Can't set current search", ex);
1107
                        return false;
1108
                }
1109
        }
1110

    
1111
        @Override
1112
        public List<SearchConditionPanel> getConditionPanels() {
1113
                return Collections.unmodifiableList(this.conditionPanels);
1114
        }
1115

    
1116
        @Override
1117
        public SearchConditionPanel getConditionPanel(String name) {
1118
                if (conditionPanels == null) {
1119
                        return null;
1120
                }
1121
                for (SearchConditionPanel panel : conditionPanels) {
1122
                        if (StringUtils.equalsIgnoreCase(name, panel.getFactory().getName())) {
1123
                                return panel;
1124
                        }
1125
                }
1126
                return null;
1127
        }
1128

    
1129
        @Override
1130
        public Expression getFilterForSelectedFeature() {
1131
                if (this.conditionPanels == null) {
1132
                        return null;
1133
                }
1134
                if (this.tabResults.getSelectedIndex() == 0) {
1135
                        int selectedRow = this.tblResults.getSelectedRow();
1136
                        if (selectedRow < 0) {
1137
                                return null;
1138
                        }
1139
                        try {
1140
                                List<Feature> features = ((SimpleFeaturesTableModelImpl) this.tblResults.getModel()).getFeatures();
1141
                                Feature feature = features.get(selectedRow);
1142

    
1143
                                ExpressionBuilder builder = ExpressionUtils.createExpressionBuilder();
1144
                                FeatureType ftype = this.store.getDefaultFeatureType();
1145
                                for (FeatureAttributeDescriptor attrdesc : ftype.getPrimaryKey()) {
1146
                                        builder.and(
1147
                                                builder.eq(
1148
                                                        builder.column(attrdesc.getName()),
1149
                                                        builder.constant(feature.get(attrdesc.getName()))
1150
                                                )
1151
                                        );
1152
                                }
1153
                                Expression filter = ExpressionUtils.createExpression(builder.toString());
1154
                                return filter;
1155
                        } catch (Exception ex) {
1156
                                LOGGER.warn("Can't build search for the selected feature.", ex);
1157
                                return null;
1158
                        }
1159
                } else {
1160
                        if (this.currentPostProcess == null) {
1161
                                return null;
1162
                        }
1163
                        int selectedRow = this.tblSearchPostProcessResults.getSelectedRow();
1164
                        if (selectedRow < 0) {
1165
                                return null;
1166
                        }
1167
                        try {
1168
                                List<Feature> features = ((SimpleFeaturesTableModelImpl) this.tblSearchPostProcessResults.getModel()).getFeatures();
1169
                                Feature feature = features.get(selectedRow);
1170

    
1171
                                ExpressionBuilder builder = ExpressionUtils.createExpressionBuilder();
1172
                                FeatureType ftype = this.postProcessStore.getDefaultFeatureType();
1173
                                for (FeatureAttributeDescriptor attrdesc : ftype.getPrimaryKey()) {
1174
                                        builder.and(
1175
                                                builder.eq(
1176
                                                        builder.column(attrdesc.getName()),
1177
                                                        builder.constant(feature.get(attrdesc.getName()))
1178
                                                )
1179
                                        );
1180
                                }
1181
                                Expression filter = ExpressionUtils.createExpression(builder.toString());
1182
                                return filter;
1183
                        } catch (Exception ex) {
1184
                                LOGGER.warn("Can't build search for the selected feature.", ex);
1185
                                return null;
1186
                        }
1187
                }
1188

    
1189
        }
1190

    
1191
        @Override
1192
        public FeatureStore getStore() {
1193
                return store;
1194
        }
1195

    
1196
        private void doOrderBy() {
1197
                I18nManager i18n = ToolsLocator.getI18nManager();
1198
                WindowManager_v2 windowManager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
1199
                FeatureQueryOrderPanel orderPanel = DALSwingLocator.getDataSwingManager().createFeatureStoreOrderPanel();
1200
                orderPanel.setStore(store);
1201
                orderPanel.put(parameters.getQuery());
1202
                Dialog dialog = windowManager.createDialog(
1203
                        orderPanel.asJComponent(),
1204
                        i18n.getTranslation("_Select_order"),
1205
                        null,
1206
                        WindowManager_v2.BUTTONS_OK_CANCEL
1207
                );
1208
                dialog.addActionListener((ActionEvent e) -> {
1209
                        if (dialog.getAction() == WindowManager_v2.BUTTON_OK) {
1210
                                orderPanel.fetch(this.parameters.getQuery());
1211
                                search();
1212
                        }
1213
                });
1214
                dialog.show(WindowManager.MODE.DIALOG);
1215
        }
1216

    
1217
        private void doCopyRows(JTable table) {
1218
                Cursor savedCursor = this.getCursor();
1219
                SimpleTaskStatus status = ToolsLocator.getTaskStatusManager().createDefaultSimpleTaskStatus("");
1220
                status.setAutoremove(true);
1221
                status.add();
1222
                this.taskStatusController.bind(status);
1223
                Thread task = new Thread(() -> {
1224
                        try {
1225
                                this.processing = true;
1226
                                this.updateComponentState();
1227
                                status.setTitle(ToolsLocator.getI18nManager().getTranslation("_Copying_rows_to_clipboard"));
1228
                                SwingUtilities.invokeLater(() -> {
1229
                                        this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
1230
                                });
1231

    
1232
                                SimpleFeaturesTableModel model = null;
1233
                                if (table.getModel() instanceof SimpleFeaturesTableModel) {
1234
                                        model = (SimpleFeaturesTableModel) table.getModel();
1235
                                }
1236

    
1237
                                String LINE_BREAK = System.lineSeparator();
1238
                                String CELL_BREAK = "\t";
1239
                                char DELIMITER = '"';
1240

    
1241
                                int[] selection = table.getSelectedRows();
1242
                                for (int i = 0; i < selection.length; i++) {
1243
                                        selection[i] = table.convertRowIndexToModel(selection[i]);
1244
                                }
1245

    
1246
                                int numCols = table.getColumnCount();
1247
                                StringBuilder excelStr = new StringBuilder();
1248
                                boolean valueIsNumeric;
1249

    
1250
                                for (int j = 0; j < numCols; j++) {
1251

    
1252
                                        excelStr.append(DELIMITER);
1253
                                        excelStr.append(escape(table.getColumnName(j), LINE_BREAK, CELL_BREAK));
1254
                                        excelStr.append(DELIMITER);
1255

    
1256
                                        if (j < numCols - 1) {
1257
                                                excelStr.append(CELL_BREAK);
1258
                                        }
1259
                                }
1260

    
1261
                                //from( 0, selection.length)
1262
                                status.setRangeOfValues(0, selection.length);
1263
                                excelStr.append(LINE_BREAK);
1264
                                for (int i : selection) {
1265
                                        status.incrementCurrentValue();
1266
                                        if (status.isCancellationRequested()) {
1267
                                                status.message("");
1268
                                                status.cancel();
1269
                                                return;
1270
                                        }
1271
                                        for (int j = 0; j < numCols; j++) {
1272
                                                valueIsNumeric = false;
1273
                                                FeatureAttributeDescriptor descriptor = null;
1274
                                                if (model != null) {
1275
                                                        descriptor = model.getFeatureDescriptor(j);
1276
                                                        if (descriptor.getDataType().isNumeric()) {
1277
                                                                if (!descriptor.hasAvailableValues()) {
1278
                                                                        valueIsNumeric = true;
1279
                                                                }
1280
                                                        }
1281
                                                }
1282
                                                if (!valueIsNumeric) {
1283
                                                        excelStr.append(DELIMITER);
1284
                                                }
1285
                                                Object value = table.getValueAt(i, j);
1286
                                                String valueStr;
1287
                                                if (descriptor != null) {
1288
                                                        valueStr = escape(descriptor.format(value), LINE_BREAK, CELL_BREAK);
1289
                                                } else {
1290
                                                        valueStr = escape(value, LINE_BREAK, CELL_BREAK);
1291

    
1292
                                                }
1293
                                                excelStr.append(valueStr);
1294

    
1295
                                                if (!valueIsNumeric) {
1296
                                                        excelStr.append(DELIMITER);
1297
                                                }
1298
                                                if (j < numCols - 1) {
1299
                                                        excelStr.append(CELL_BREAK);
1300
                                                }
1301
                                        }
1302
                                        excelStr.append(LINE_BREAK);
1303
                                }
1304
                                String toStr = excelStr.toString();
1305

    
1306
                                doPostCopyRows(status, toStr);
1307
                                SwingUtilities.invokeLater(() -> {
1308
                                        status.setTitle(ToolsLocator.getI18nManager().getTranslation("_Copy_ended"));
1309
                                        status.terminate();
1310
                                });
1311

    
1312
                        } catch (Exception ex) {
1313
                                LOGGER.warn("Not able to copy rows to the clipboard", ex);
1314
                                status.message("Not able to copy rows to the clipboard");
1315
                                status.abort();
1316
                        } finally {
1317
                                this.processing = false;
1318
                                SwingUtilities.invokeLater(() -> {
1319
                                        this.setCursor(savedCursor);
1320
                                });
1321
                                this.updateComponentState();
1322
                        }
1323
                }, "SearchPanelCopyRows");
1324
                task.start();
1325
        }
1326

    
1327
        private void doPostCopyRows(SimpleTaskStatus status, String toStr) {
1328
                if (!SwingUtilities.isEventDispatchThread()) {
1329
                        SwingUtilities.invokeLater(() -> {
1330
                                doPostCopyRows(status, toStr);
1331
                        });
1332
                        return;
1333
                }
1334
                ToolsSwingLocator.getToolsSwingManager().putInClipboard(toStr);
1335
//        StringSelection sel = new StringSelection(toStr);
1336
//        Clipboard CLIPBOARD = Toolkit.getDefaultToolkit().getSystemClipboard();
1337
//        CLIPBOARD.setContents(sel, null);            
1338
        }
1339

    
1340
        private String escape(Object cell, String LINE_BREAK, String CELL_BREAK) {
1341
                return (cell == null ? "" : cell.toString()
1342
                        .replace(CELL_BREAK, " ")
1343
                        .replace("\n", " ")
1344
                        .replace("\r", " "));
1345
        }
1346

    
1347
        @Override
1348
        public ImageIcon loadImage(String imageName) {
1349
                String name = FilenameUtils.getBaseName(imageName);
1350
                IconTheme theme = ToolsSwingLocator.getIconThemeManager().getDefault();
1351
                if (theme.exists(name)) {
1352
                        return theme.get(name);
1353
                }
1354
                URL url = this.getClass().getResource(name + ".png");
1355
                if (url == null) {
1356
                        return null;
1357
                }
1358
                return new ImageIcon(url);
1359
        }
1360

    
1361
        @Override
1362
        public int getSelectedFeatureCount() {
1363
                if (this.conditionPanels == null) {
1364
                        return 0;
1365
                }
1366
                if (this.currentPostProcess == null || this.tabResults.getSelectedIndex() == 0) {
1367
                        return this.tblResults.getSelectedRowCount();
1368
                }
1369
                return this.tblSearchPostProcessResults.getSelectedRowCount();
1370
        }
1371

    
1372
        @Override
1373
        public JComponent getActionButton(String name) {
1374
                ActionButtons actionButton = this.actions.get(name);
1375
                if (actionButton == null) {
1376
                        return null;
1377
                }
1378
                return actionButton.button;
1379
        }
1380

    
1381
        @Override
1382
        public void setShowActions(boolean showActions) {
1383
                this.showActions = showActions;
1384
        }
1385

    
1386
        @Override
1387
        public boolean isShowActions() {
1388
                return this.showActions;
1389
        }
1390

    
1391
        public static String getAttributeDescriptorLabel(FeatureAttributeDescriptor attrdesc, String tableName) {
1392
                String theLabel;
1393
                int theUseLabels;
1394
                if (useLabels == null) {
1395
                        Tags tags = attrdesc.getTags();
1396
                        if (tags.has(DAL_USE_LABELS)) {
1397
                                theUseLabels = tags.getInt(DAL_USE_LABELS, USE_LABELS_NO);
1398
                        } else {
1399
                                if (attrdesc.getFeatureType() != null) {
1400
                                        tags = attrdesc.getFeatureType().getTags();
1401
                                        theUseLabels = tags.getInt(DAL_USE_LABELS, USE_LABELS_NO);
1402
                                } else {
1403
                                        theUseLabels = USE_LABELS_NO;
1404
                                }
1405
                        }
1406
                } else {
1407
                        theUseLabels = useLabels;
1408
                }
1409
                switch (theUseLabels) {
1410
                        case USE_LABELS_YES:
1411
                                if (StringUtils.isBlank(tableName)) {
1412
                                        theLabel = attrdesc.getLocalizedLabel();
1413
                                } else {
1414
                                        theLabel = String.format("%s [%s]", attrdesc.getLocalizedLabel(), tableName);
1415
                                }
1416
                                break;
1417
                        default:
1418
                        case USE_LABELS_NO:
1419
                                if (StringUtils.isBlank(tableName)) {
1420
                                        theLabel = attrdesc.getName();
1421
                                } else {
1422
                                        theLabel = String.format("%s [%s]", attrdesc.getName(), tableName);
1423
                                }
1424
                                break;
1425
                        case USE_LABELS_BOTH:
1426
                                if (StringUtils.isBlank(tableName)) {
1427
                                        theLabel = String.format("%s [%s]", attrdesc.getLocalizedLabel(), attrdesc.getName());
1428
                                } else {
1429
                                        theLabel = String.format("%s [%s/%s]", attrdesc.getLocalizedLabel(), attrdesc.getName(), tableName);
1430
                                }
1431
                                break;
1432
                }
1433
                return theLabel;
1434
        }
1435

    
1436
        private void doCalculatedColumns() {
1437
                WindowManager_v2 winmanager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
1438
                I18nManager i18n = ToolsLocator.getI18nManager();
1439
                final FeatureQueryCalculatedColumnsPanel panel = new DefaultFeatureQueryCalculatedColumnsPanel();
1440
                panel.setStore(this.store);
1441
                panel.put(this.parameters.getQuery());
1442
                final Dialog dialog = winmanager.createDialog(
1443
                        panel.asJComponent(),
1444
                        i18n.getTranslation("_Calculated_columns"),
1445
                        null,
1446
                        WindowManager_v2.BUTTONS_OK_CANCEL
1447
                );
1448
                dialog.addActionListener((ActionEvent e) -> {
1449
                        if (dialog.getAction() == WindowManager_v2.BUTTONS_OK) {
1450
                                panel.fetch(this.parameters.getQuery());
1451
                                search();
1452
                        }
1453
                });
1454
                dialog.show(WindowManager.MODE.DIALOG);
1455
        }
1456

    
1457
        private void doGroupBy() {
1458
                DataStoreProviderFactory dataFactory = this.store.getProviderFactory();
1459
                int allowGroupBy = ((FeatureStoreProviderFactory) dataFactory).allowGroupBy();
1460
                if (allowGroupBy != DataType.YES) {
1461
                        // FIXME: mensaje al usaurio.
1462
                        I18nManager i18n = ToolsLocator.getI18nManager();
1463
                        ThreadSafeDialogsManager dialogs = ToolsSwingLocator.getThreadSafeDialogsManager();
1464
                        dialogs.messageDialog(
1465
                                i18n.getTranslation("_The_group_function_is_not_available_for_this_table"),
1466
                                i18n.getTranslation("_Information"),
1467
                                JOptionPane.INFORMATION_MESSAGE
1468
                        );
1469
                        return;
1470
                }
1471

    
1472
                WindowManager_v2 winmanager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
1473
                I18nManager i18n = ToolsLocator.getI18nManager();
1474
                final FeatureQueryGroupByPanel panelGroupBy = new DefaultFeatureQueryGroupByPanel();
1475
                panelGroupBy.setStore(this.store);
1476
                panelGroupBy.put(this.parameters.getQuery());
1477
                final Dialog dialog = winmanager.createDialog(
1478
                        panelGroupBy.asJComponent(),
1479
                        i18n.getTranslation("_Select_group_columns_and_aggregate_functions"),
1480
                        null,
1481
                        WindowManager_v2.BUTTONS_OK_CANCEL
1482
                );
1483
                dialog.addActionListener((ActionEvent e) -> {
1484
                        if (dialog.getAction() == WindowManager_v2.BUTTONS_OK) {
1485
                                panelGroupBy.fetch(this.parameters.getQuery());
1486
                                search();
1487
                        }
1488
                });
1489
                dialog.show(WindowManager.MODE.DIALOG);
1490
        }
1491

    
1492
        private void doSelectResultColumnNames() {
1493
                WindowManager_v2 winmanager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
1494
                I18nManager i18n = ToolsLocator.getI18nManager();
1495
                final FeatureAttributesSelectionPanel panelSelectColumns = DALSwingLocator.getManager().createFeatureAttributeSelectionPanel();
1496
                panelSelectColumns.allowCalculatedAttributes(false);
1497
                FeatureType ftype = this.getFeatureType();
1498
                try {
1499
                        Feature f = store.findFirst(this.parameters.getQuery());
1500
                        if (f != null) {
1501
                                ftype = f.getType();
1502
                        }
1503
                } catch (Throwable ex) {
1504
                        LOGGER.warn("Can't retrieve the feature type from the first feature.", ex);
1505
                }
1506
                panelSelectColumns.setFeatureType(ftype);
1507
                panelSelectColumns.setSelectedNames(this.parameters.getResultColumnNames());
1508
                final Dialog dialog = winmanager.createDialog(
1509
                        panelSelectColumns.asJComponent(),
1510
                        i18n.getTranslation("_Select_the_columns_to_display"),
1511
                        null,
1512
                        WindowManager_v2.BUTTONS_OK_CANCEL
1513
                );
1514
                dialog.addActionListener((ActionEvent e) -> {
1515
                        if (dialog.getAction() == WindowManager_v2.BUTTONS_OK) {
1516
                                this.setResultColumnNames(panelSelectColumns.getSelectedNames());
1517
                                search();
1518
                        }
1519
                });
1520
                dialog.show(WindowManager.MODE.DIALOG);
1521
        }
1522

    
1523
        @Override
1524
        public void put(SearchParameters inParams) {
1525
                this.parameters = (DefaultSearchParameters) inParams;
1526
                for (SearchConditionPanel conditionPanel : this.conditionPanels) {
1527
                        try {
1528
                                conditionPanel.put(inParams);
1529
                        } catch (Exception ex) {
1530
                                LOGGER.warn("Can't open panel", ex);
1531
                        }
1532
                }
1533
                this.tabSearchMode.setSelectedIndex(inParams.getSearchMode());
1534
//        this.resetTable();
1535

    
1536
        }
1537

    
1538
        private FeatureQuery getQuery() {
1539
                FeatureQuery query;
1540
                try {
1541
                        int searchMode = this.tabSearchMode.getSelectedIndex();
1542
                        SearchConditionPanel panel = this.conditionPanels.get(searchMode);
1543
                        Expression filter = panel.get();
1544
                        if (searchMode != PANEL_ADVANCED) {
1545
                                this.conditionPanels.get(PANEL_ADVANCED).set(filter);
1546
                        }
1547
                        query = (FeatureQuery) this.parameters.getQuery().clone();
1548
                        query.retrievesAllAttributes();
1549
                        if (ExpressionUtils.isPhraseEmpty(filter)) {
1550
                                return query;
1551
                        }
1552
                        query.setFilter(filter);
1553
                        query.retrievesAllAttributes();
1554
                        return query;
1555
                } catch (Exception ex) {
1556
                        LOGGER.warn("Can't build query.", ex);
1557
                        return null;
1558
                }
1559
        }
1560

    
1561
        @Override
1562
        public SearchParameters fetch(SearchParameters outParams) {
1563
                // Actualiza el fquery del parameters con los paneles
1564
                for (SearchConditionPanel conditionPanel : conditionPanels) {
1565
                        try {
1566
                                conditionPanel.fetch(this.parameters);
1567
                        } catch (Exception ex) {
1568
                                LOGGER.warn("Panel not able to fetch values", ex);
1569
                        }
1570
                }
1571

    
1572
                // Actualiza el filtro con el panel activo
1573
                int searchMode = this.tabSearchMode.getSelectedIndex();
1574
                SearchConditionPanel panel = this.conditionPanels.get(searchMode);
1575
                Expression filter = panel.get();
1576
                if (searchMode != PANEL_ADVANCED) {
1577
                        this.conditionPanels.get(PANEL_ADVANCED).set(filter);
1578
                }
1579
                this.parameters.setSearchMode(searchMode);
1580
                FeatureQuery query = (FeatureQuery) this.parameters.getQuery();
1581
                this.lastQuery = query.getCopy();
1582
                query.retrievesAllAttributes();
1583
                query.clearFilter();
1584
                if (!ExpressionUtils.isPhraseEmpty(filter)) {
1585
                        query.setFilter(filter);
1586
                        query.retrievesAllAttributes();
1587
                }
1588

    
1589
                if (outParams == null) {
1590
                        return this.parameters.getCopy();
1591
                }
1592
                outParams.copyFrom(this.parameters.getCopy());
1593
                return outParams;
1594
        }
1595

    
1596
        public static void selfRegister() {
1597
                IconTheme theme;
1598
                try {
1599
                   theme = ToolsSwingLocator.getIconThemeManager().getCurrent();
1600
                } catch(ReferenceNotRegisteredException ex) {
1601
                    return;
1602
                }
1603
                String[][] iconNames = new String[][]{
1604
                        new String[]{"dalswing", "featurestore-column"},
1605
                        new String[]{"dalswing", "featurestore-foreing-key"},
1606
                        new String[]{"dalswing", "featurestore-table"},
1607
                        new String[]{"dalswing", "search-action-select"},
1608
                        new String[]{"dalswing", "search-action-select-add"},
1609
                        new String[]{"dalswing", "search-action-select-filter"},
1610
                        new String[]{"dalswing", "search-nullbehavior-null"},
1611
                        new String[]{"dalswing", "search-nullbehavior-true"},
1612
                        new String[]{"dalswing", "search-nullbehavior-false2"}
1613

    
1614
                };
1615
                for (String[] icon : iconNames) {
1616
                        URL url = DefaultSearchPanel.class.getResource(icon[1] + ".png");
1617
                        theme.registerDefault("DALSwing", icon[0], icon[1], null, url);
1618
                }
1619

    
1620
                ConfigurableActionsMamager cfgActionsManager = ToolsUtilLocator.getConfigurableActionsMamager();
1621
                cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new UseLabelsYesAction());
1622
                cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new UseLabelsNoAction());
1623
                cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new UseLabelsBothAction());
1624
                cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new SelectColumnsAction());
1625
                cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new CalculatedColumnsAction());
1626
                cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new GroupByAction());
1627
                cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new OrderByAction());
1628
        }
1629

    
1630
        private void doSelectSearchPostprocess() throws DataException {
1631
                DataSwingManager manager = DALSwingLocator.getDataSwingManager();
1632
                Map<String, SearchPostProcessFactory> searchPostProcessFactoryMap = manager.getSearchPostProcess();
1633

    
1634
                JPopupMenu menu = new JPopupMenu();
1635
                for (String factory : searchPostProcessFactoryMap.keySet()) {
1636
                        JMenuItem item;
1637
                        item = new JMenuItem(factory);
1638
                        SearchParameters searchParams = this.fetch(this.parameters.getCopy());
1639
                        FeatureQuery myQuery = searchParams.getQuery().getCopy();
1640
//            item.addActionListener(new SearchPostProcessListener(this.store, myQuery, manager.getSearchPostProcess(factory)));
1641
                        item.addActionListener((ActionEvent e) -> {
1642
                                doSearchPostProcess(store, myQuery, manager.getSearchPostProcess(factory), searchParams);
1643
                        });
1644
                        menu.add(item);
1645
                }
1646
                menu.show(this.btnSearchPostProcess, 0, this.btnSearchPostProcess.getHeight());
1647
        }
1648

    
1649
        private void doExecuteSearchPostProcess(
1650
                FeatureStore input,
1651
                FeatureQuery query,
1652
                SearchPostProcessFactory factory,
1653
                DynObject parameters
1654
        ) {
1655
                Cursor savedCursor = this.getCursor();
1656
                SimpleTaskStatus status = ToolsLocator.getTaskStatusManager().createDefaultSimpleTaskStatus("");
1657
                status.setAutoremove(true);
1658
                status.add();
1659
                this.taskStatusController.bind(status);
1660
                Thread task = new Thread(() -> {
1661
                        try {
1662
                                SwingUtilities.invokeLater(() -> {
1663
                                        this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
1664
                                });
1665
                                this.processing = true;
1666
                                this.updateComponentState();
1667
                                SearchPostProcess process = factory.createProcess(factory, input, query, parameters);
1668

    
1669
                                if (parameters != null) {
1670
                                        process.setParameters(parameters);
1671
                                }
1672
                                //Ejecutar el execute en thread para no bloquear el software
1673
                                SearchPostProcess.SearchPostProcessResult output = process.execute(input, query, parameters, status);
1674
                                if (output != null) {
1675
                                        this.postProcessStore = output.getStore();
1676
                                        this.postProcessQuery = output.getQuery();
1677

    
1678
                                        doLoadSearchPostProccessResults(this.postProcessStore);
1679

    
1680
                                }
1681
                                this.currentPostProcess = factory.getName();
1682
                                status.terminate();
1683

    
1684
                        } catch (Exception ex) {
1685
                                LOGGER.warn("SearchPostProcess not able to be executed.", ex);
1686
                                resetPostProcessTable();
1687
                                status.setTitle(ToolsLocator.getI18nManager().getTranslation("_Error_in_post_process_operation"));
1688
                                status.message("");
1689
                                status.abort();
1690
                        } finally {
1691
                                SwingUtilities.invokeLater(() -> {
1692
                                        this.setCursor(savedCursor);
1693
                                });
1694
                                this.processing = false;
1695
                                this.updateComponentState();
1696
                        }
1697
                }, "ExecuteSearchPostProcess");
1698

    
1699
                task.start();
1700

    
1701
        }
1702

    
1703
        private void doLoadSearchPostProccessResults(FeatureStore input) {
1704
                if (!SwingUtilities.isEventDispatchThread()) {
1705
                        SwingUtilities.invokeLater(() -> {
1706
                                doLoadSearchPostProccessResults(input);
1707
                        });
1708
                        return;
1709
                }
1710

    
1711
                final List<Feature> featuresSearchPostProccessResults;
1712
                final FeatureQuery finalQuery;
1713
                finalQuery = null;
1714
                try {
1715
                        this.tabResults.setEnabledAt(1, true);
1716
                        this.tabResults.setSelectedIndex(1);
1717
                        featuresSearchPostProccessResults = input.getFeatures(finalQuery, 20);
1718
                        FacadeOfAFeaturePagingHelper facadeSearchPostProccessResults = (FacadeOfAFeaturePagingHelper) featuresSearchPostProccessResults;
1719
                        FeatureType ftypeSearchPostProccessResults = facadeSearchPostProccessResults.getFeaturePagingHelper().getFeatureSet().getDefaultFeatureType();
1720
                        // al modelo le pasamos el ftype de esas features
1721
                        resultPostProcessModel = new SimpleFeaturesTableModelImpl(
1722
                                ftypeSearchPostProccessResults,
1723
                                this.parameters.getResultColumnNames(),
1724
                                featuresSearchPostProccessResults
1725
                        );
1726

    
1727
                        I18nManager i18n = ToolsLocator.getI18nManager();
1728
                        TableModel oldmodel = tblSearchPostProcessResults.getModel();
1729
                        tblSearchPostProcessResults.setModel(resultPostProcessModel);
1730
                        resultPostProcessModel.setCellRenderers(tblSearchPostProcessResults);
1731
                        if (oldmodel instanceof SimpleFeaturesTableModel) {
1732
                                ((SimpleFeaturesTableModel) oldmodel).dispose();
1733
                        }
1734
                        updateNumberElementsMsg(resultPostProcessModel);
1735
//            if (resultPostProcessModel.hasErrors()) {
1736
//                lblMsg.setText("_Errors_occurred_load_search_post_process");
1737
//            } else {
1738
//                lblMsg.setText(String.format("%d " + i18n.getTranslation("_elements"), resultPostProcessModel.getRowCount()));
1739
//            }
1740
                } catch (Exception ex) {
1741
                        resetPostProcessTable();
1742
                        LOGGER.warn("SearchPostProcess not able to be executed. Can't get features or create table model", ex);
1743
                }
1744
        }
1745

    
1746
        private void updateComponentState() {
1747
                if (!SwingUtilities.isEventDispatchThread()) {
1748
                        SwingUtilities.invokeLater(this::updateComponentState);
1749
                        return;
1750
                }
1751
                this.pgbStatus.setVisible(processing);
1752
                this.setEnabled(!processing);
1753
        }
1754

    
1755
        private void resetPostProcessTable() {
1756
                if (!SwingUtilities.isEventDispatchThread()) {
1757
                        SwingUtilities.invokeLater(this::resetPostProcessTable);
1758
                        return;
1759
                }
1760

    
1761
                this.tblSearchPostProcessResults.setModel(new DefaultTableModel());
1762
        }
1763

    
1764
        private void doSearchPostProcess(FeatureStore store, FeatureQuery query, SearchPostProcessFactory factory, SearchParameters searchParams) {
1765
                if (factory.hasProcessParameters()) {
1766
                        DynObject parametersPostProcess = factory.createProcessParameters(store, query, searchParams);
1767
                        JDynForm form = DynFormLocator.getDynFormManager().createJDynForm(parametersPostProcess);
1768
                        form.setLayoutMode(JDynForm.USE_SEPARATORS);
1769

    
1770
                        I18nManager i18n = ToolsLocator.getI18nManager();
1771
                        WindowManager_v2 windowManager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
1772

    
1773
                        Dialog dialog = windowManager.createDialog(
1774
                                form.asJComponent(),
1775
                                i18n.getTranslation("_Postprocess_parameters"),
1776
                                i18n.getTranslation(
1777
                                        "_Parameters_for_XpostprocessNameX_postprocess_on_XtableNameX",
1778
                                        new String[]{
1779
                                                factory.getName(),
1780
                                                this.store.getName()
1781
                                        }
1782
                                ),
1783
                                WindowManager_v2.BUTTONS_OK_CANCEL);
1784

    
1785
                        ToolsSwingUtils.ensureRowsCols(dialog.asJComponent(), 20, 60, 30, 100);
1786
                        dialog.addActionListener((ActionEvent e2) -> {
1787
                                if (dialog.getAction() == WindowManager_v2.BUTTON_OK) {
1788
                                        form.getValues(parametersPostProcess); // actualiza el valor de lo los parametros con los valores introducidos por el usuario
1789
                                        doExecuteSearchPostProcess(store, query, factory, parametersPostProcess);
1790
                                        this.postProcessParams = parametersPostProcess;
1791
                                }
1792
                        });
1793

    
1794
                        dialog.show(WindowManager.MODE.DIALOG);
1795

    
1796
                } else {
1797
                        doExecuteSearchPostProcess(store, query, factory, null);
1798
                }
1799
        }
1800

    
1801
        private void updateNumberElementsMsg(SimpleFeaturesTableModel model) {
1802
                I18nManager i18n = ToolsLocator.getI18nManager();
1803

    
1804
                if (model.hasErrors()) {
1805
                        this.taskStatusController.setTitle(i18n.getTranslation("_Errors_occurred_load_search_post_process"));
1806
                } else {
1807
                        this.taskStatusController.setTitle(String.format("%d " + i18n.getTranslation("_elements"), model.getRowCount()));
1808
                }
1809
        }
1810

    
1811
        @Override
1812
        public boolean isVisible(Object component) {
1813
                if (this.filterOnlyMode) {
1814
                        if (component instanceof GroupByAction) {
1815
                                return false;
1816
                        }
1817
//            if( component instanceof OrderByAction ) {
1818
//                return false;
1819
//            }
1820
//            if( component instanceof CalculatedColumnsAction ) {
1821
//                return false;
1822
//            }
1823
                }
1824
                return true;
1825
        }
1826

    
1827
        @Override
1828
        public boolean isEnabled(Object component) {
1829
                if (component instanceof GroupByAction) {
1830
                        DataStoreProviderFactory dataFactory = this.store.getProviderFactory();
1831
                        int allowGroupBy = ((FeatureStoreProviderFactory) dataFactory).allowGroupBy();
1832
                        if (allowGroupBy != DataType.YES) {
1833
                                return false;
1834
                        }
1835
                }
1836
                return true;
1837
        }
1838

    
1839
        @Override
1840
        public void setFilterOnlyMode(boolean filterOnlyMode) {
1841
                if (this.conditionPanels != null) {
1842
                        throw new IllegalStateException("Cannot change filter-only-mode after invoking asJComponent.");
1843
                }
1844
                this.filterOnlyMode = filterOnlyMode;
1845
                this.showActions = false;
1846
        }
1847

    
1848
        @Override
1849
        public boolean isFilterOnlyMode() {
1850
                return this.filterOnlyMode;
1851
        }
1852

    
1853
        @Override
1854
        public Feature getLastSelectedFeature() {
1855
                return this.lastSelectedFeature;
1856
        }
1857

    
1858
        @Override
1859
        public Object getProperty(String name) {
1860
                return this.propertiesHelper.getProperty(name);
1861
        }
1862

    
1863
        @Override
1864
        public void setProperty(String name, Object value) {
1865
                this.propertiesHelper.setProperty(name, value);
1866
        }
1867

    
1868
        @Override
1869
        public Map<String, Object> getProperties() {
1870
                return this.propertiesHelper.getProperties();
1871
        }
1872

    
1873
}