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

History | View | Annotate | Download (62.3 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.HistoryController;
116
import org.gvsig.tools.swing.api.task.TaskStatusController;
117
import org.gvsig.tools.swing.api.threadsafedialogs.ThreadSafeDialogsManager;
118
import org.gvsig.tools.task.SimpleTaskStatus;
119
import org.gvsig.tools.util.PropertiesSupportHelper;
120

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

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

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

    
140
        public static class UseLabelsYesAction extends AbstractAction {
141

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

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

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

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

    
166
        public static class UseLabelsNoAction extends AbstractAction {
167

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

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

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

    
191
        public static class UseLabelsBothAction extends AbstractAction {
192

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

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

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

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

    
217
        public static class SelectColumnsAction extends AbstractAction {
218

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

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

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

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

    
244
        public static class CalculatedColumnsAction extends AbstractAction {
245

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

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

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

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

    
271
        public static class GroupByAction extends AbstractAction {
272

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

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

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

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

    
298
        public static class OrderByAction extends AbstractAction {
299

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

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

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

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

    
325
        private class TablePopupMenu extends JPopupMenu {
326

    
327
                public final JTable table;
328

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

    
341
        private class ActionButtons {
342

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

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

    
354
        public static class SearchActionContext extends AbstractDALActionContext {
355

    
356
                private final DefaultSearchPanel panel;
357

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

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

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

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

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

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

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

    
469
        private List<SearchConditionPanel> conditionPanels;
470

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

    
478
        private String currentPostProcess;
479

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

    
486
        private boolean processing;
487
        private JComponent configurableActions;
488

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
713
                this.historyController.setFilter(null);
714

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

    
723
                                case ID_SETVALUE:
724
                                        if (b.getCurrentValue() == null) {
725
                                                return;
726
                                        }
727
                                        DefaultSearchParameters searchParams;
728
                                        try {
729
                                                searchParams = b.getCurrentValue().getCopy();
730
                                                searchParams.fix(this.getFeatureType());
731
                                                // TODO: habria que comprobar y preguntar al usuario de forma
732
                                                // similar a lo que se hace en DefaultFeatureQueryCalculatedColumnsPanel.doRemove
733
                                        } catch (Exception ex) {
734
                                                LOGGER.warn("Not been able to clone export parameters", ex);
735
                                                return;
736
                                        }
737
                                        clear();
738
                                        put(searchParams);
739
                                        Thread th = new Thread(() -> {
740
                                                doSearch(searchParams);
741
                                        });
742
                                        th.start();
743
                                        break;
744
                        }
745
                };
746
                this.historyController.addActionListener(bookmarksAndHistoryListener);
747
                this.bookmarksController.addActionListener(bookmarksAndHistoryListener);
748
                this.addComponentListener(new ComponentAdapter() {
749
                        @Override
750
                        public void componentHidden(ComponentEvent e) {
751
                                dispose();
752
                        }
753
                });
754

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

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

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

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

    
778
                //this.tblResults.add
779
                if (this.bookmarks.hasBookmark(this.store.getName())) {
780
                        Bookmark<DefaultSearchParameters> initBookmark = this.bookmarks.get(this.store.getName());
781
                        DefaultSearchParameters initSearchParams = initBookmark.getValue().getCopy();
782
                        put(initSearchParams);
783
                        Thread th = new Thread(() -> {
784
                                doSearch(initSearchParams);
785
                        });
786
                        th.start();
787
                        return;
788
                }
789

    
790
                this.tabResults.addChangeListener((ChangeEvent evt) -> {
791
                        SwingUtilities.invokeLater(() -> {
792
                                if (tabResults.getSelectedIndex() == 0) {
793
                                        updateNumberElementsMsg(resultModel);
794
                                } else {
795
                                        updateNumberElementsMsg(resultPostProcessModel);
796
                                }
797
                        });
798
                });
799
                if (this.filterOnlyMode) {
800
                        this.btnSearchPostProcess.setVisible(false);
801
                }
802
                clear();
803
                search();
804
        }
805

    
806
        private void doShowCellInDialog() {
807
                int row = this.tblResults.getSelectedRow();
808
                if (row < 0) {
809
                        return;
810
                }
811
                int col = this.tblResults.getSelectedColumn();
812
                if (col < 0) {
813
                        return;
814
                }
815
                String s = Objects.toString(this.tblResults.getValueAt(row, col), null);
816
                if (StringUtils.isBlank(s)) {
817
                        return;
818
                }
819
                ToolsSwingLocator.getToolsSwingManager().showZoomDialog(
820
                        this,
821
                        this.tblResults.getColumnName(col),
822
                        s,
823
                        false
824
                );
825
        }
826

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

    
836
        @Override
837
        public void setEnabled(boolean enabled) {
838
                if (!SwingUtilities.isEventDispatchThread()) {
839
                        SwingUtilities.invokeLater(() -> {
840
                                setEnabled(enabled);
841
                        });
842
                        return;
843
                }
844

    
845
                if (this.conditionPanels == null) {
846
                        this.initComponents();
847
                }
848
                for (SearchConditionPanel conditionPanel : conditionPanels) {
849
                        conditionPanel.setEnabled(enabled);
850
                }
851

    
852
                this.btnClear.setEnabled(enabled);
853
                this.btnSearch.setEnabled(enabled);
854
                for (ActionButtons actionButton : actions.values()) {
855
                        actionButton.action.setEnabled(enabled);
856
                }
857
                this.btnSearchPostProcess.setEnabled(enabled);
858
                //bookmarkController,historyController,configurableActions
859
        }
860

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

    
886
                        }
887
                }
888
                resultColumnNames.removeAll(toDeleteAlreadyDontExist);
889
                resetTable();
890
        }
891

    
892
        @Override
893
        public FeatureQuery getLastQuery() {
894
                return this.lastQuery;
895
        }
896

    
897
        public boolean isValid(StringBuilder message) {
898
                int searchMode = this.tabSearchMode.getSelectedIndex();
899
                SearchConditionPanel panel = this.conditionPanels.get(searchMode);
900
                boolean valid = panel.isValid(message);
901
                return valid;
902
        }
903

    
904
        @Override
905
        public void search() {
906
                StringBuilder message = new StringBuilder();
907
                if (!this.isValid(message)) {
908
                        ThreadSafeDialogsManager dialogManager = ToolsSwingLocator.getThreadSafeDialogsManager();
909
                        dialogManager.messageDialog(
910
                                "_The_specified_search_condition_is_not_valid",
911
                                "_Search",
912
                                JOptionPane.WARNING_MESSAGE
913
                        );
914
                        return;
915
                }
916
                lblMsg.setText(ToolsLocator.getI18nManager().getTranslation("_Searching") + "...");
917
                setEnabled(false);
918
                Thread th = new Thread(() -> {
919
                        try {
920
                                SearchParameters searchParams;
921
                                try {
922
                                        searchParams = this.fetch(this.parameters.getCopy()); // esto lo actualiza a la ultima // decidir si se devuelve clonado
923

    
924
                                        Date date = Calendar.getInstance().getTime();
925
                                        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
926
                                        String strDate = dateFormat.format(date);
927
                                        searchParams.setName("Params: " + strDate);
928
                                } catch (Exception ex) {
929
                                        LOGGER.warn("Not able to create search parameters.", ex);
930
                                        this.taskStatusController.setTitle(ToolsLocator.getI18nManager().getTranslation("_Errors_fetching_new_query") + "...");
931
                                        resetTable();
932
                                        return;
933
                                }
934
                                doSearch(searchParams);
935
                        } catch (Exception ex) {
936
                                LOGGER.warn("Search panel has errors during the search", ex);
937
                                resetTable();
938
                        } finally {
939
                                SwingUtilities.invokeLater(() -> {
940
                                        setEnabled(true);
941
                                });
942
                        }
943
                });
944
                th.start();
945
        }
946

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

    
1013
        private Map<String, TableCellRenderer> getCustomRenderers(SearchParameters parameters) {
1014
                FeatureType ft = this.store.getDefaultFeatureTypeQuietly();
1015
                HashMap<String, TableCellRenderer> renderers = new HashMap<String, TableCellRenderer>();
1016
                for (FeatureAttributeDescriptor attr : ft) {
1017
                        if (attr.getDataType().isNumeric()) {
1018
//                renderers.put(attr.getName(), new ColorRangeRenderer(attr, 20, 50));
1019
                        }
1020
                }
1021
                return renderers;
1022
        }
1023

    
1024
        private void resetTable() {
1025
                if (!SwingUtilities.isEventDispatchThread()) {
1026
                        SwingUtilities.invokeLater(this::resetTable);
1027
                        return;
1028
                }
1029
                List<String> resultColumnNames = null;
1030
                try {
1031
                        resultColumnNames = this.parameters.getResultColumnNames();
1032
                } catch (Exception ex) {
1033

    
1034
                }
1035
                FeatureType ftype = this.store.getDefaultFeatureTypeQuietly();
1036
                SimpleFeaturesTableModelImpl emptyTableModel = new SimpleFeaturesTableModelImpl(
1037
                        ftype,
1038
                        resultColumnNames,
1039
                        null
1040
                );
1041
                this.tblResults.setModel(emptyTableModel);
1042

    
1043
        }
1044

    
1045
        public void setResultColumnNames(List<String> names) {
1046
                this.parameters.getResultColumnNames().clear();
1047
                this.parameters.getResultColumnNames().addAll(names);
1048
//        if (this.conditionPanels == null) {
1049
//            return;
1050
//        }
1051
//        SimpleFeaturesTableModelImpl model;
1052
////        model = (SimpleFeaturesTableModel) this.tblResults.getModel();
1053
//        List<Feature> features = store.getFeatures(this.parameters.getQuery());
1054
//        FacadeOfAFeaturePagingHelper facade = (FacadeOfAFeaturePagingHelper) features;
1055
//        FeatureType ftype = facade.getFeaturePagingHelper().getFeatureSet().getDefaultFeatureType();
1056
//        model = new SimpleFeaturesTableModelImpl(
1057
//                ftype,
1058
//                this.parameters.getResultColumnNames(),
1059
//                features
1060
//        );
1061
//        tblResults.setModel(model);
1062
        }
1063

    
1064
        @Override
1065
        public boolean setFilter(Expression filter) {
1066
                try {
1067
                        if (this.conditionPanels == null) {
1068
                                this.initComponents();
1069
                        }
1070
                        if (ExpressionUtils.isPhraseEmpty(filter)) {
1071
                                this.clear();
1072
                                return true;
1073
                        }
1074
                        int panel = 0;
1075
                        int selected = PANEL_ADVANCED;
1076
                        for (SearchConditionPanel conditionPanel : conditionPanels) {
1077
                                if (panel != PANEL_ADVANCED && conditionPanel.set(filter)) {
1078
                                        selected = panel;
1079
                                }
1080
                                panel++;
1081
                        }
1082
                        this.tabSearchMode.setSelectedIndex(selected);
1083

    
1084
//            SimpleFeaturesTableModel model = new SimpleFeaturesTableModel(this.getStore());
1085
//            tblResults.setModel(model);
1086
//            lblMsg.setText("");
1087
                        return true;
1088
                } catch (Exception ex) {
1089
                        LOGGER.warn("Can't set current search", ex);
1090
                        return false;
1091
                }
1092
        }
1093

    
1094
        @Override
1095
        public List<SearchConditionPanel> getConditionPanels() {
1096
                return Collections.unmodifiableList(this.conditionPanels);
1097
        }
1098

    
1099
        @Override
1100
        public SearchConditionPanel getConditionPanel(String name) {
1101
                if (conditionPanels == null) {
1102
                        return null;
1103
                }
1104
                for (SearchConditionPanel panel : conditionPanels) {
1105
                        if (StringUtils.equalsIgnoreCase(name, panel.getFactory().getName())) {
1106
                                return panel;
1107
                        }
1108
                }
1109
                return null;
1110
        }
1111

    
1112
        @Override
1113
        public Expression getFilterForSelectedFeature() {
1114
                if (this.conditionPanels == null) {
1115
                        return null;
1116
                }
1117
                if (this.tabResults.getSelectedIndex() == 0) {
1118
                        int selectedRow = this.tblResults.getSelectedRow();
1119
                        if (selectedRow < 0) {
1120
                                return null;
1121
                        }
1122
                        try {
1123
                                List<Feature> features = ((SimpleFeaturesTableModelImpl) this.tblResults.getModel()).getFeatures();
1124
                                Feature feature = features.get(selectedRow);
1125

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

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

    
1172
        }
1173

    
1174
        @Override
1175
        public FeatureStore getStore() {
1176
                return store;
1177
        }
1178

    
1179
        private void doOrderBy() {
1180
                I18nManager i18n = ToolsLocator.getI18nManager();
1181
                WindowManager_v2 windowManager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
1182
                FeatureQueryOrderPanel orderPanel = DALSwingLocator.getDataSwingManager().createFeatureStoreOrderPanel();
1183
                orderPanel.setStore(store);
1184
                orderPanel.put(parameters.getQuery());
1185
                Dialog dialog = windowManager.createDialog(
1186
                        orderPanel.asJComponent(),
1187
                        i18n.getTranslation("_Select_order"),
1188
                        null,
1189
                        WindowManager_v2.BUTTONS_OK_CANCEL
1190
                );
1191
                dialog.addActionListener((ActionEvent e) -> {
1192
                        if (dialog.getAction() == WindowManager_v2.BUTTON_OK) {
1193
                                orderPanel.fetch(this.parameters.getQuery());
1194
                                search();
1195
                        }
1196
                });
1197
                dialog.show(WindowManager.MODE.DIALOG);
1198
        }
1199

    
1200
        private void doCopyRows(JTable table) {
1201
                Cursor savedCursor = this.getCursor();
1202
                SimpleTaskStatus status = ToolsLocator.getTaskStatusManager().createDefaultSimpleTaskStatus("");
1203
                status.setAutoremove(true);
1204
                status.add();
1205
                this.taskStatusController.bind(status);
1206
                Thread task = new Thread(() -> {
1207
                        try {
1208
                                this.processing = true;
1209
                                this.updateComponentState();
1210
                                status.setTitle(ToolsLocator.getI18nManager().getTranslation("_Copying_rows_to_clipboard"));
1211
                                SwingUtilities.invokeLater(() -> {
1212
                                        this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
1213
                                });
1214

    
1215
                                SimpleFeaturesTableModel model = null;
1216
                                if (table.getModel() instanceof SimpleFeaturesTableModel) {
1217
                                        model = (SimpleFeaturesTableModel) table.getModel();
1218
                                }
1219

    
1220
                                String LINE_BREAK = System.lineSeparator();
1221
                                String CELL_BREAK = "\t";
1222
                                char DELIMITER = '"';
1223

    
1224
                                int[] selection = table.getSelectedRows();
1225
                                for (int i = 0; i < selection.length; i++) {
1226
                                        selection[i] = table.convertRowIndexToModel(selection[i]);
1227
                                }
1228

    
1229
                                int numCols = table.getColumnCount();
1230
                                StringBuilder excelStr = new StringBuilder();
1231
                                boolean valueIsNumeric;
1232

    
1233
                                for (int j = 0; j < numCols; j++) {
1234

    
1235
                                        excelStr.append(DELIMITER);
1236
                                        excelStr.append(escape(table.getColumnName(j), LINE_BREAK, CELL_BREAK));
1237
                                        excelStr.append(DELIMITER);
1238

    
1239
                                        if (j < numCols - 1) {
1240
                                                excelStr.append(CELL_BREAK);
1241
                                        }
1242
                                }
1243

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

    
1275
                                                }
1276
                                                excelStr.append(valueStr);
1277

    
1278
                                                if (!valueIsNumeric) {
1279
                                                        excelStr.append(DELIMITER);
1280
                                                }
1281
                                                if (j < numCols - 1) {
1282
                                                        excelStr.append(CELL_BREAK);
1283
                                                }
1284
                                        }
1285
                                        excelStr.append(LINE_BREAK);
1286
                                }
1287
                                String toStr = excelStr.toString();
1288

    
1289
                                doPostCopyRows(status, toStr);
1290
                                SwingUtilities.invokeLater(() -> {
1291
                                        status.setTitle(ToolsLocator.getI18nManager().getTranslation("_Copy_ended"));
1292
                                        status.terminate();
1293
                                });
1294

    
1295
                        } catch (Exception ex) {
1296
                                LOGGER.warn("Not able to copy rows to the clipboard", ex);
1297
                                status.message("Not able to copy rows to the clipboard");
1298
                                status.abort();
1299
                        } finally {
1300
                                this.processing = false;
1301
                                SwingUtilities.invokeLater(() -> {
1302
                                        this.setCursor(savedCursor);
1303
                                });
1304
                                this.updateComponentState();
1305
                        }
1306
                }, "SearchPanelCopyRows");
1307
                task.start();
1308
        }
1309

    
1310
        private void doPostCopyRows(SimpleTaskStatus status, String toStr) {
1311
                if (!SwingUtilities.isEventDispatchThread()) {
1312
                        SwingUtilities.invokeLater(() -> {
1313
                                doPostCopyRows(status, toStr);
1314
                        });
1315
                        return;
1316
                }
1317
                ToolsSwingLocator.getToolsSwingManager().putInClipboard(toStr);
1318
//        StringSelection sel = new StringSelection(toStr);
1319
//        Clipboard CLIPBOARD = Toolkit.getDefaultToolkit().getSystemClipboard();
1320
//        CLIPBOARD.setContents(sel, null);            
1321
        }
1322

    
1323
        private String escape(Object cell, String LINE_BREAK, String CELL_BREAK) {
1324
                return (cell == null ? "" : cell.toString()
1325
                        .replace(CELL_BREAK, " ")
1326
                        .replace("\n", " ")
1327
                        .replace("\r", " "));
1328
        }
1329

    
1330
        @Override
1331
        public ImageIcon loadImage(String imageName) {
1332
                String name = FilenameUtils.getBaseName(imageName);
1333
                IconTheme theme = ToolsSwingLocator.getIconThemeManager().getDefault();
1334
                if (theme.exists(name)) {
1335
                        return theme.get(name);
1336
                }
1337
                URL url = this.getClass().getResource(name + ".png");
1338
                if (url == null) {
1339
                        return null;
1340
                }
1341
                return new ImageIcon(url);
1342
        }
1343

    
1344
        @Override
1345
        public int getSelectedFeatureCount() {
1346
                if (this.conditionPanels == null) {
1347
                        return 0;
1348
                }
1349
                if (this.currentPostProcess == null || this.tabResults.getSelectedIndex() == 0) {
1350
                        return this.tblResults.getSelectedRowCount();
1351
                }
1352
                return this.tblSearchPostProcessResults.getSelectedRowCount();
1353
        }
1354

    
1355
        @Override
1356
        public JComponent getActionButton(String name) {
1357
                ActionButtons actionButton = this.actions.get(name);
1358
                if (actionButton == null) {
1359
                        return null;
1360
                }
1361
                return actionButton.button;
1362
        }
1363

    
1364
        @Override
1365
        public void setShowActions(boolean showActions) {
1366
                this.showActions = showActions;
1367
        }
1368

    
1369
        @Override
1370
        public boolean isShowActions() {
1371
                return this.showActions;
1372
        }
1373

    
1374
        public static String getAttributeDescriptorLabel(FeatureAttributeDescriptor attrdesc, String tableName) {
1375
                String theLabel;
1376
                int theUseLabels;
1377
                if (useLabels == null) {
1378
                        Tags tags = attrdesc.getTags();
1379
                        if (tags.has(DAL_USE_LABELS)) {
1380
                                theUseLabels = tags.getInt(DAL_USE_LABELS, USE_LABELS_NO);
1381
                        } else {
1382
                                if (attrdesc.getFeatureType() != null) {
1383
                                        tags = attrdesc.getFeatureType().getTags();
1384
                                        theUseLabels = tags.getInt(DAL_USE_LABELS, USE_LABELS_NO);
1385
                                } else {
1386
                                        theUseLabels = USE_LABELS_NO;
1387
                                }
1388
                        }
1389
                } else {
1390
                        theUseLabels = useLabels;
1391
                }
1392
                switch (theUseLabels) {
1393
                        case USE_LABELS_YES:
1394
                                if (StringUtils.isBlank(tableName)) {
1395
                                        theLabel = attrdesc.getLocalizedLabel();
1396
                                } else {
1397
                                        theLabel = String.format("%s [%s]", attrdesc.getLocalizedLabel(), tableName);
1398
                                }
1399
                                break;
1400
                        default:
1401
                        case USE_LABELS_NO:
1402
                                if (StringUtils.isBlank(tableName)) {
1403
                                        theLabel = attrdesc.getName();
1404
                                } else {
1405
                                        theLabel = String.format("%s [%s]", attrdesc.getName(), tableName);
1406
                                }
1407
                                break;
1408
                        case USE_LABELS_BOTH:
1409
                                if (StringUtils.isBlank(tableName)) {
1410
                                        theLabel = String.format("%s [%s]", attrdesc.getLocalizedLabel(), attrdesc.getName());
1411
                                } else {
1412
                                        theLabel = String.format("%s [%s/%s]", attrdesc.getLocalizedLabel(), attrdesc.getName(), tableName);
1413
                                }
1414
                                break;
1415
                }
1416
                return theLabel;
1417
        }
1418

    
1419
        private void doCalculatedColumns() {
1420
                WindowManager_v2 winmanager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
1421
                I18nManager i18n = ToolsLocator.getI18nManager();
1422
                final FeatureQueryCalculatedColumnsPanel panel = new DefaultFeatureQueryCalculatedColumnsPanel();
1423
                panel.setStore(this.store);
1424
                panel.put(this.parameters.getQuery());
1425
                final Dialog dialog = winmanager.createDialog(
1426
                        panel.asJComponent(),
1427
                        i18n.getTranslation("_Calculated_columns"),
1428
                        null,
1429
                        WindowManager_v2.BUTTONS_OK_CANCEL
1430
                );
1431
                dialog.addActionListener((ActionEvent e) -> {
1432
                        if (dialog.getAction() == WindowManager_v2.BUTTONS_OK) {
1433
                                panel.fetch(this.parameters.getQuery());
1434
                                search();
1435
                        }
1436
                });
1437
                dialog.show(WindowManager.MODE.DIALOG);
1438
        }
1439

    
1440
        private void doGroupBy() {
1441
                DataStoreProviderFactory dataFactory = this.store.getProviderFactory();
1442
                int allowGroupBy = ((FeatureStoreProviderFactory) dataFactory).allowGroupBy();
1443
                if (allowGroupBy != DataType.YES) {
1444
                        // FIXME: mensaje al usaurio.
1445
                        I18nManager i18n = ToolsLocator.getI18nManager();
1446
                        ThreadSafeDialogsManager dialogs = ToolsSwingLocator.getThreadSafeDialogsManager();
1447
                        dialogs.messageDialog(
1448
                                i18n.getTranslation("_The_group_function_is_not_available_for_this_table"),
1449
                                i18n.getTranslation("_Information"),
1450
                                JOptionPane.INFORMATION_MESSAGE
1451
                        );
1452
                        return;
1453
                }
1454

    
1455
                WindowManager_v2 winmanager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
1456
                I18nManager i18n = ToolsLocator.getI18nManager();
1457
                final FeatureQueryGroupByPanel panelGroupBy = new DefaultFeatureQueryGroupByPanel();
1458
                panelGroupBy.setStore(this.store);
1459
                panelGroupBy.put(this.parameters.getQuery());
1460
                final Dialog dialog = winmanager.createDialog(
1461
                        panelGroupBy.asJComponent(),
1462
                        i18n.getTranslation("_Select_group_columns_and_aggregate_functions"),
1463
                        null,
1464
                        WindowManager_v2.BUTTONS_OK_CANCEL
1465
                );
1466
                dialog.addActionListener((ActionEvent e) -> {
1467
                        if (dialog.getAction() == WindowManager_v2.BUTTONS_OK) {
1468
                                panelGroupBy.fetch(this.parameters.getQuery());
1469
                                search();
1470
                        }
1471
                });
1472
                dialog.show(WindowManager.MODE.DIALOG);
1473
        }
1474

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

    
1506
        @Override
1507
        public void put(SearchParameters inParams) {
1508
                this.parameters = (DefaultSearchParameters) inParams;
1509
                for (SearchConditionPanel conditionPanel : this.conditionPanels) {
1510
                        try {
1511
                                conditionPanel.put(inParams);
1512
                        } catch (Exception ex) {
1513
                                LOGGER.warn("Can't open panel", ex);
1514
                        }
1515
                }
1516
                this.tabSearchMode.setSelectedIndex(inParams.getSearchMode());
1517
//        this.resetTable();
1518

    
1519
        }
1520

    
1521
        private FeatureQuery getQuery() {
1522
                FeatureQuery query;
1523
                try {
1524
                        int searchMode = this.tabSearchMode.getSelectedIndex();
1525
                        SearchConditionPanel panel = this.conditionPanels.get(searchMode);
1526
                        Expression filter = panel.get();
1527
                        if (searchMode != PANEL_ADVANCED) {
1528
                                this.conditionPanels.get(PANEL_ADVANCED).set(filter);
1529
                        }
1530
                        query = (FeatureQuery) this.parameters.getQuery().clone();
1531
                        query.retrievesAllAttributes();
1532
                        if (ExpressionUtils.isPhraseEmpty(filter)) {
1533
                                return query;
1534
                        }
1535
                        query.setFilter(filter);
1536
                        query.retrievesAllAttributes();
1537
                        return query;
1538
                } catch (Exception ex) {
1539
                        LOGGER.warn("Can't build query.", ex);
1540
                        return null;
1541
                }
1542
        }
1543

    
1544
        @Override
1545
        public SearchParameters fetch(SearchParameters outParams) {
1546
                // Actualiza el fquery del parameters con los paneles
1547
                for (SearchConditionPanel conditionPanel : conditionPanels) {
1548
                        try {
1549
                                conditionPanel.fetch(this.parameters);
1550
                        } catch (Exception ex) {
1551
                                LOGGER.warn("Panel not able to fetch values", ex);
1552
                        }
1553
                }
1554

    
1555
                // Actualiza el filtro con el panel activo
1556
                int searchMode = this.tabSearchMode.getSelectedIndex();
1557
                SearchConditionPanel panel = this.conditionPanels.get(searchMode);
1558
                Expression filter = panel.get();
1559
                if (searchMode != PANEL_ADVANCED) {
1560
                        this.conditionPanels.get(PANEL_ADVANCED).set(filter);
1561
                }
1562
                this.parameters.setSearchMode(searchMode);
1563
                FeatureQuery query = (FeatureQuery) this.parameters.getQuery();
1564
                this.lastQuery = query.getCopy();
1565
                query.retrievesAllAttributes();
1566
                query.clearFilter();
1567
                if (!ExpressionUtils.isPhraseEmpty(filter)) {
1568
                        query.setFilter(filter);
1569
                        query.retrievesAllAttributes();
1570
                }
1571

    
1572
                if (outParams == null) {
1573
                        return this.parameters.getCopy();
1574
                }
1575
                outParams.copyFrom(this.parameters.getCopy());
1576
                return outParams;
1577
        }
1578

    
1579
        public static void selfRegister() {
1580
                IconTheme theme;
1581
                try {
1582
                   theme = ToolsSwingLocator.getIconThemeManager().getCurrent();
1583
                } catch(ReferenceNotRegisteredException ex) {
1584
                    return;
1585
                }
1586
                String[][] iconNames = new String[][]{
1587
                        new String[]{"dalswing", "featurestore-column"},
1588
                        new String[]{"dalswing", "featurestore-foreing-key"},
1589
                        new String[]{"dalswing", "featurestore-table"},
1590
                        new String[]{"dalswing", "search-action-select"},
1591
                        new String[]{"dalswing", "search-action-select-add"},
1592
                        new String[]{"dalswing", "search-action-select-filter"},
1593
                        new String[]{"dalswing", "search-nullbehavior-null"},
1594
                        new String[]{"dalswing", "search-nullbehavior-true"},
1595
                        new String[]{"dalswing", "search-nullbehavior-false2"}
1596

    
1597
                };
1598
                for (String[] icon : iconNames) {
1599
                        URL url = DefaultSearchPanel.class.getResource(icon[1] + ".png");
1600
                        theme.registerDefault("DALSwing", icon[0], icon[1], null, url);
1601
                }
1602

    
1603
                ConfigurableActionsMamager cfgActionsManager = ToolsUtilLocator.getConfigurableActionsMamager();
1604
                cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new UseLabelsYesAction());
1605
                cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new UseLabelsNoAction());
1606
                cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new UseLabelsBothAction());
1607
                cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new SelectColumnsAction());
1608
                cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new CalculatedColumnsAction());
1609
                cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new GroupByAction());
1610
                cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new OrderByAction());
1611
        }
1612

    
1613
        private void doSelectSearchPostprocess() throws DataException {
1614
                DataSwingManager manager = DALSwingLocator.getDataSwingManager();
1615
                Map<String, SearchPostProcessFactory> searchPostProcessFactoryMap = manager.getSearchPostProcess();
1616

    
1617
                JPopupMenu menu = new JPopupMenu();
1618
                for (String factory : searchPostProcessFactoryMap.keySet()) {
1619
                        JMenuItem item;
1620
                        item = new JMenuItem(factory);
1621
                        SearchParameters searchParams = this.fetch(this.parameters.getCopy());
1622
                        FeatureQuery myQuery = searchParams.getQuery().getCopy();
1623
//            item.addActionListener(new SearchPostProcessListener(this.store, myQuery, manager.getSearchPostProcess(factory)));
1624
                        item.addActionListener((ActionEvent e) -> {
1625
                                doSearchPostProcess(store, myQuery, manager.getSearchPostProcess(factory), searchParams);
1626
                        });
1627
                        menu.add(item);
1628
                }
1629
                menu.show(this.btnSearchPostProcess, 0, this.btnSearchPostProcess.getHeight());
1630
        }
1631

    
1632
        private void doExecuteSearchPostProcess(
1633
                FeatureStore input,
1634
                FeatureQuery query,
1635
                SearchPostProcessFactory factory,
1636
                DynObject parameters
1637
        ) {
1638
                Cursor savedCursor = this.getCursor();
1639
                SimpleTaskStatus status = ToolsLocator.getTaskStatusManager().createDefaultSimpleTaskStatus("");
1640
                status.setAutoremove(true);
1641
                status.add();
1642
                this.taskStatusController.bind(status);
1643
                Thread task = new Thread(() -> {
1644
                        try {
1645
                                SwingUtilities.invokeLater(() -> {
1646
                                        this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
1647
                                });
1648
                                this.processing = true;
1649
                                this.updateComponentState();
1650
                                SearchPostProcess process = factory.createProcess(factory, input, query, parameters);
1651

    
1652
                                if (parameters != null) {
1653
                                        process.setParameters(parameters);
1654
                                }
1655
                                //Ejecutar el execute en thread para no bloquear el software
1656
                                SearchPostProcess.SearchPostProcessResult output = process.execute(input, query, parameters, status);
1657
                                if (output != null) {
1658
                                        this.postProcessStore = output.getStore();
1659
                                        this.postProcessQuery = output.getQuery();
1660

    
1661
                                        doLoadSearchPostProccessResults(this.postProcessStore);
1662

    
1663
                                }
1664
                                this.currentPostProcess = factory.getName();
1665
                                status.terminate();
1666

    
1667
                        } catch (Exception ex) {
1668
                                LOGGER.warn("SearchPostProcess not able to be executed.", ex);
1669
                                resetPostProcessTable();
1670
                                status.setTitle(ToolsLocator.getI18nManager().getTranslation("_Error_in_post_process_operation"));
1671
                                status.message("");
1672
                                status.abort();
1673
                        } finally {
1674
                                SwingUtilities.invokeLater(() -> {
1675
                                        this.setCursor(savedCursor);
1676
                                });
1677
                                this.processing = false;
1678
                                this.updateComponentState();
1679
                        }
1680
                }, "ExecuteSearchPostProcess");
1681

    
1682
                task.start();
1683

    
1684
        }
1685

    
1686
        private void doLoadSearchPostProccessResults(FeatureStore input) {
1687
                if (!SwingUtilities.isEventDispatchThread()) {
1688
                        SwingUtilities.invokeLater(() -> {
1689
                                doLoadSearchPostProccessResults(input);
1690
                        });
1691
                        return;
1692
                }
1693

    
1694
                final List<Feature> featuresSearchPostProccessResults;
1695
                final FeatureQuery finalQuery;
1696
                finalQuery = null;
1697
                try {
1698
                        this.tabResults.setEnabledAt(1, true);
1699
                        this.tabResults.setSelectedIndex(1);
1700
                        featuresSearchPostProccessResults = input.getFeatures(finalQuery, 20);
1701
                        FacadeOfAFeaturePagingHelper facadeSearchPostProccessResults = (FacadeOfAFeaturePagingHelper) featuresSearchPostProccessResults;
1702
                        FeatureType ftypeSearchPostProccessResults = facadeSearchPostProccessResults.getFeaturePagingHelper().getFeatureSet().getDefaultFeatureType();
1703
                        // al modelo le pasamos el ftype de esas features
1704
                        resultPostProcessModel = new SimpleFeaturesTableModelImpl(
1705
                                ftypeSearchPostProccessResults,
1706
                                this.parameters.getResultColumnNames(),
1707
                                featuresSearchPostProccessResults
1708
                        );
1709

    
1710
                        I18nManager i18n = ToolsLocator.getI18nManager();
1711
                        TableModel oldmodel = tblSearchPostProcessResults.getModel();
1712
                        tblSearchPostProcessResults.setModel(resultPostProcessModel);
1713
                        resultPostProcessModel.setCellRenderers(tblSearchPostProcessResults);
1714
                        if (oldmodel instanceof SimpleFeaturesTableModel) {
1715
                                ((SimpleFeaturesTableModel) oldmodel).dispose();
1716
                        }
1717
                        updateNumberElementsMsg(resultPostProcessModel);
1718
//            if (resultPostProcessModel.hasErrors()) {
1719
//                lblMsg.setText("_Errors_occurred_load_search_post_process");
1720
//            } else {
1721
//                lblMsg.setText(String.format("%d " + i18n.getTranslation("_elements"), resultPostProcessModel.getRowCount()));
1722
//            }
1723
                } catch (Exception ex) {
1724
                        resetPostProcessTable();
1725
                        LOGGER.warn("SearchPostProcess not able to be executed. Can't get features or create table model", ex);
1726
                }
1727
        }
1728

    
1729
        private void updateComponentState() {
1730
                if (!SwingUtilities.isEventDispatchThread()) {
1731
                        SwingUtilities.invokeLater(this::updateComponentState);
1732
                        return;
1733
                }
1734
                this.pgbStatus.setVisible(processing);
1735
                this.setEnabled(!processing);
1736
        }
1737

    
1738
        private void resetPostProcessTable() {
1739
                if (!SwingUtilities.isEventDispatchThread()) {
1740
                        SwingUtilities.invokeLater(this::resetPostProcessTable);
1741
                        return;
1742
                }
1743

    
1744
                this.tblSearchPostProcessResults.setModel(new DefaultTableModel());
1745
        }
1746

    
1747
        private void doSearchPostProcess(FeatureStore store, FeatureQuery query, SearchPostProcessFactory factory, SearchParameters searchParams) {
1748
                if (factory.hasProcessParameters()) {
1749
                        DynObject parametersPostProcess = factory.createProcessParameters(store, query, searchParams);
1750
                        JDynForm form = DynFormLocator.getDynFormManager().createJDynForm(parametersPostProcess);
1751
                        form.setLayoutMode(JDynForm.USE_SEPARATORS);
1752

    
1753
                        I18nManager i18n = ToolsLocator.getI18nManager();
1754
                        WindowManager_v2 windowManager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
1755

    
1756
                        Dialog dialog = windowManager.createDialog(
1757
                                form.asJComponent(),
1758
                                i18n.getTranslation("_Postprocess_parameters"),
1759
                                i18n.getTranslation(
1760
                                        "_Parameters_for_XpostprocessNameX_postprocess_on_XtableNameX",
1761
                                        new String[]{
1762
                                                factory.getName(),
1763
                                                this.store.getName()
1764
                                        }
1765
                                ),
1766
                                WindowManager_v2.BUTTONS_OK_CANCEL);
1767

    
1768
                        ToolsSwingUtils.ensureRowsCols(dialog.asJComponent(), 20, 60, 30, 100);
1769
                        dialog.addActionListener((ActionEvent e2) -> {
1770
                                if (dialog.getAction() == WindowManager_v2.BUTTON_OK) {
1771
                                        form.getValues(parametersPostProcess); // actualiza el valor de lo los parametros con los valores introducidos por el usuario
1772
                                        doExecuteSearchPostProcess(store, query, factory, parametersPostProcess);
1773
                                        this.postProcessParams = parametersPostProcess;
1774
                                }
1775
                        });
1776

    
1777
                        dialog.show(WindowManager.MODE.DIALOG);
1778

    
1779
                } else {
1780
                        doExecuteSearchPostProcess(store, query, factory, null);
1781
                }
1782
        }
1783

    
1784
        private void updateNumberElementsMsg(SimpleFeaturesTableModel model) {
1785
                I18nManager i18n = ToolsLocator.getI18nManager();
1786

    
1787
                if (model.hasErrors()) {
1788
                        this.taskStatusController.setTitle(i18n.getTranslation("_Errors_occurred_load_search_post_process"));
1789
                } else {
1790
                        this.taskStatusController.setTitle(String.format("%d " + i18n.getTranslation("_elements"), model.getRowCount()));
1791
                }
1792
        }
1793

    
1794
        @Override
1795
        public boolean isVisible(Object component) {
1796
                if (this.filterOnlyMode) {
1797
                        if (component instanceof GroupByAction) {
1798
                                return false;
1799
                        }
1800
//            if( component instanceof OrderByAction ) {
1801
//                return false;
1802
//            }
1803
//            if( component instanceof CalculatedColumnsAction ) {
1804
//                return false;
1805
//            }
1806
                }
1807
                return true;
1808
        }
1809

    
1810
        @Override
1811
        public boolean isEnabled(Object component) {
1812
                if (component instanceof GroupByAction) {
1813
                        DataStoreProviderFactory dataFactory = this.store.getProviderFactory();
1814
                        int allowGroupBy = ((FeatureStoreProviderFactory) dataFactory).allowGroupBy();
1815
                        if (allowGroupBy != DataType.YES) {
1816
                                return false;
1817
                        }
1818
                }
1819
                return true;
1820
        }
1821

    
1822
        @Override
1823
        public void setFilterOnlyMode(boolean filterOnlyMode) {
1824
                if (this.conditionPanels != null) {
1825
                        throw new IllegalStateException("Cannot change filter-only-mode after invoking asJComponent.");
1826
                }
1827
                this.filterOnlyMode = filterOnlyMode;
1828
                this.showActions = false;
1829
        }
1830

    
1831
        @Override
1832
        public boolean isFilterOnlyMode() {
1833
                return this.filterOnlyMode;
1834
        }
1835

    
1836
        @Override
1837
        public Feature getLastSelectedFeature() {
1838
                return this.lastSelectedFeature;
1839
        }
1840

    
1841
        @Override
1842
        public Object getProperty(String name) {
1843
                return this.propertiesHelper.getProperty(name);
1844
        }
1845

    
1846
        @Override
1847
        public void setProperty(String name, Object value) {
1848
                this.propertiesHelper.setProperty(name, value);
1849
        }
1850

    
1851
        @Override
1852
        public Map<String, Object> getProperties() {
1853
                return this.propertiesHelper.getProperties();
1854
        }
1855

    
1856
}