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

History | View | Annotate | Download (86 KB)

1 44259 jjdelcerro
package org.gvsig.fmap.dal.swing.impl.searchpanel;
2
3 44351 jjdelcerro
import java.awt.BorderLayout;
4 44263 jjdelcerro
import java.awt.Cursor;
5
import java.awt.FlowLayout;
6 44259 jjdelcerro
import java.awt.event.ActionEvent;
7
import java.awt.event.ActionListener;
8 45100 jjdelcerro
import java.awt.event.ComponentAdapter;
9
import java.awt.event.ComponentEvent;
10 45192 jjdelcerro
import java.awt.event.KeyAdapter;
11
import java.awt.event.KeyEvent;
12 47228 fdiaz
import java.io.ByteArrayOutputStream;
13 46571 fdiaz
import java.io.File;
14
import java.nio.charset.Charset;
15 46517 fdiaz
import java.sql.SQLException;
16 44829 omartinez
import java.text.DateFormat;
17
import java.text.SimpleDateFormat;
18 44259 jjdelcerro
import java.util.ArrayList;
19 44829 omartinez
import java.util.Calendar;
20 44263 jjdelcerro
import java.util.Collection;
21 44707 jjdelcerro
import java.util.Collections;
22 44829 omartinez
import java.util.Date;
23 44275 jjdelcerro
import java.util.HashMap;
24 47228 fdiaz
import java.util.Iterator;
25 44259 jjdelcerro
import java.util.List;
26 44275 jjdelcerro
import java.util.Map;
27 45192 jjdelcerro
import java.util.Objects;
28 44351 jjdelcerro
import javax.swing.AbstractAction;
29 44263 jjdelcerro
import javax.swing.Action;
30 44351 jjdelcerro
import static javax.swing.Action.ACTION_COMMAND_KEY;
31
import static javax.swing.Action.NAME;
32 44275 jjdelcerro
import javax.swing.BorderFactory;
33 44259 jjdelcerro
import javax.swing.ImageIcon;
34 44263 jjdelcerro
import javax.swing.JButton;
35 44259 jjdelcerro
import javax.swing.JComponent;
36 46571 fdiaz
import static javax.swing.JFileChooser.FILES_ONLY;
37 45537 jolivas
import javax.swing.JMenuItem;
38 44764 jjdelcerro
import javax.swing.JOptionPane;
39 46571 fdiaz
import static javax.swing.JOptionPane.YES_OPTION;
40 45537 jolivas
import javax.swing.JPopupMenu;
41 45695 omartinez
import javax.swing.JTable;
42 45191 jjdelcerro
import javax.swing.ListSelectionModel;
43 44262 jjdelcerro
import javax.swing.SwingUtilities;
44 45537 jolivas
import javax.swing.event.ChangeEvent;
45 44259 jjdelcerro
import javax.swing.event.ListSelectionEvent;
46
import javax.swing.event.ListSelectionListener;
47 46571 fdiaz
import javax.swing.filechooser.FileFilter;
48 45100 jjdelcerro
import javax.swing.table.DefaultTableModel;
49 46051 omartinez
import javax.swing.table.TableCellRenderer;
50 44262 jjdelcerro
import javax.swing.table.TableModel;
51 44259 jjdelcerro
import org.apache.commons.io.FilenameUtils;
52 44262 jjdelcerro
import org.apache.commons.lang.mutable.MutableObject;
53 46900 jjdelcerro
import org.apache.commons.lang3.ArrayUtils;
54 44351 jjdelcerro
import org.apache.commons.lang3.StringUtils;
55 45162 omartinez
import org.apache.commons.lang3.mutable.MutableLong;
56 46571 fdiaz
import org.apache.commons.lang3.tuple.ImmutablePair;
57 47228 fdiaz
import org.apache.commons.lang3.tuple.Pair;
58 44351 jjdelcerro
import org.gvsig.configurableactions.ConfigurableActionsMamager;
59 44259 jjdelcerro
import org.gvsig.expressionevaluator.Expression;
60
import org.gvsig.expressionevaluator.ExpressionBuilder;
61 47184 jjdelcerro
import org.gvsig.expressionevaluator.ExpressionEvaluatorLocator;
62
import org.gvsig.expressionevaluator.ExpressionEvaluatorManager;
63 44259 jjdelcerro
import org.gvsig.expressionevaluator.ExpressionUtils;
64 46571 fdiaz
import static org.gvsig.filedialogchooser.FileDialogChooser.SAVE_DIALOG;
65 44351 jjdelcerro
import static org.gvsig.fmap.dal.DataManager.USE_LABELS_BOTH;
66
import static org.gvsig.fmap.dal.DataManager.USE_LABELS_NO;
67
import static org.gvsig.fmap.dal.DataManager.USE_LABELS_YES;
68 44281 jjdelcerro
import org.gvsig.fmap.dal.DataStore;
69 44855 jjdelcerro
import org.gvsig.fmap.dal.DataStoreProviderFactory;
70 44262 jjdelcerro
import org.gvsig.fmap.dal.complements.Search;
71 45247 omartinez
import org.gvsig.fmap.dal.exception.DataException;
72 44259 jjdelcerro
import org.gvsig.fmap.dal.feature.Feature;
73
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
74 44712 jjdelcerro
import org.gvsig.fmap.dal.feature.FeatureQuery;
75 46900 jjdelcerro
import org.gvsig.fmap.dal.feature.FeatureSelection;
76 47228 fdiaz
import org.gvsig.fmap.dal.feature.FeatureSet;
77 44259 jjdelcerro
import org.gvsig.fmap.dal.feature.FeatureStore;
78 44712 jjdelcerro
import org.gvsig.fmap.dal.feature.FeatureStoreProviderFactory;
79 44259 jjdelcerro
import org.gvsig.fmap.dal.feature.FeatureType;
80 44794 omartinez
import org.gvsig.fmap.dal.feature.paging.FacadeOfAFeaturePagingHelper;
81 44281 jjdelcerro
import org.gvsig.fmap.dal.swing.AbstractDALActionFactory.AbstractDALActionContext;
82
import org.gvsig.fmap.dal.swing.DALActionFactory;
83 44259 jjdelcerro
import org.gvsig.fmap.dal.swing.DALSwingLocator;
84 45537 jolivas
import org.gvsig.fmap.dal.swing.DataSwingManager;
85 44712 jjdelcerro
import org.gvsig.fmap.dal.swing.featurequery.FeatureQueryCalculatedColumnsPanel;
86
import org.gvsig.fmap.dal.swing.featurequery.FeatureQueryOrderPanel;
87 45425 jjdelcerro
import org.gvsig.fmap.dal.swing.featuretable.SimpleFeaturesTableModel;
88 46536 fdiaz
import org.gvsig.fmap.dal.swing.featuretype.FeatureAttributesSelectionPanel;
89 46863 jjdelcerro
import static org.gvsig.fmap.dal.swing.impl.DefaultDALSwingLibrary.LIBRARY_NAME;
90 44712 jjdelcerro
import org.gvsig.fmap.dal.swing.impl.featurequery.DefaultFeatureQueryCalculatedColumnsPanel;
91 45537 jolivas
import org.gvsig.fmap.dal.swing.impl.featuretable.SimpleFeaturesTableModelImpl;
92
import org.gvsig.fmap.dal.swing.searchPostProcess.SearchPostProcess;
93
import org.gvsig.fmap.dal.swing.searchPostProcess.SearchPostProcessFactory;
94 46536 fdiaz
import org.gvsig.fmap.dal.swing.searchpanel.FeatureStoreSearchPanel;
95
import org.gvsig.fmap.dal.swing.searchpanel.SearchConditionPanel;
96
import org.gvsig.fmap.dal.swing.searchpanel.SearchConditionPanel.SearchConditionPanelFactory;
97 44829 omartinez
import org.gvsig.fmap.dal.swing.searchpanel.SearchParameters;
98 46536 fdiaz
import org.gvsig.tools.ToolsLocator;
99 45274 omartinez
import org.gvsig.tools.bookmarksandhistory.Bookmark;
100 44829 omartinez
import org.gvsig.tools.bookmarksandhistory.Bookmarks;
101
import org.gvsig.tools.bookmarksandhistory.History;
102 46536 fdiaz
import org.gvsig.tools.dataTypes.DataType;
103 45100 jjdelcerro
import org.gvsig.tools.dispose.Disposable;
104
import org.gvsig.tools.dispose.DisposeUtils;
105 45537 jolivas
import org.gvsig.tools.dynform.DynFormLocator;
106
import org.gvsig.tools.dynform.JDynForm;
107
import org.gvsig.tools.dynobject.DynObject;
108 46571 fdiaz
import org.gvsig.tools.folders.FoldersManager;
109 46536 fdiaz
import org.gvsig.tools.i18n.I18nManager;
110
import org.gvsig.tools.swing.api.ActionListenerSupport;
111 47417 jjdelcerro
import org.gvsig.tools.swing.api.Component;
112 45379 jjdelcerro
import org.gvsig.tools.swing.api.SupportIsEnable;
113
import org.gvsig.tools.swing.api.SupportIsVisible;
114 46536 fdiaz
import org.gvsig.tools.swing.api.ToolsSwingLocator;
115
import org.gvsig.tools.swing.api.ToolsSwingManager;
116 45705 jolivas
import org.gvsig.tools.swing.api.ToolsSwingUtils;
117 44829 omartinez
import org.gvsig.tools.swing.api.bookmarkshistory.ActionEventWithCurrentValue;
118
import static org.gvsig.tools.swing.api.bookmarkshistory.ActionEventWithCurrentValue.ID_GETVALUE;
119 46536 fdiaz
import static org.gvsig.tools.swing.api.bookmarkshistory.ActionEventWithCurrentValue.ID_SETNAME;
120 44829 omartinez
import static org.gvsig.tools.swing.api.bookmarkshistory.ActionEventWithCurrentValue.ID_SETVALUE;
121
import org.gvsig.tools.swing.api.bookmarkshistory.BookmarksController;
122 46463 fdiaz
import org.gvsig.tools.swing.api.bookmarkshistory.BookmarksController.BookmarkEvent;
123 44829 omartinez
import org.gvsig.tools.swing.api.bookmarkshistory.HistoryController;
124 46051 omartinez
import org.gvsig.tools.swing.api.task.TaskStatusController;
125 44764 jjdelcerro
import org.gvsig.tools.swing.api.threadsafedialogs.ThreadSafeDialogsManager;
126 46536 fdiaz
import org.gvsig.tools.swing.api.windowmanager.Dialog;
127
import org.gvsig.tools.swing.api.windowmanager.WindowManager;
128
import org.gvsig.tools.swing.api.windowmanager.WindowManager_v2;
129 46051 omartinez
import org.gvsig.tools.task.SimpleTaskStatus;
130 46971 jjdelcerro
import org.gvsig.tools.util.ListBuilder;
131 46010 jjdelcerro
import org.gvsig.tools.util.PropertiesSupportHelper;
132 46536 fdiaz
import org.gvsig.tools.util.ToolsUtilLocator;
133
import org.slf4j.Logger;
134
import org.slf4j.LoggerFactory;
135 44259 jjdelcerro
136
/**
137
 *
138
 * @author jjdelcerro
139
 */
140 44707 jjdelcerro
@SuppressWarnings({"UseSpecificCatch"})
141 44259 jjdelcerro
public class DefaultSearchPanel
142 46063 omartinez
        extends DefaultSearchPanelView2
143
        implements FeatureStoreSearchPanel, SupportIsEnable, SupportIsVisible {
144 44259 jjdelcerro
145 46063 omartinez
        private static final Logger LOGGER = LoggerFactory.getLogger(DefaultSearchPanel.class);
146 46571 fdiaz
147 47228 fdiaz
        private static final String EXPORT_TO_TSV_TITLE="_Export_to_TSV";
148
        private static final String EXPORT_TO_TSV_LASTPATHID="exporttotsv.lastpath";
149 46571 fdiaz
        private static final String TSV_EXTENSION="tsv";
150 44829 omartinez
151 46063 omartinez
        private BookmarksController bookmarksController;
152
        private HistoryController historyController;
153
        private FeatureQuery lastQuery;
154
        private Feature lastSelectedFeature;
155
        private final PropertiesSupportHelper propertiesHelper;
156
        private TaskStatusController taskStatusController;
157 46485 fdiaz
        private boolean automaticallySearch;
158 46517 fdiaz
        private String lastErrorMessage;
159 46665 jjdelcerro
        private boolean initialized;
160
        private boolean postProcessEnabled;
161
        private boolean groupByEnabled;
162 47417 jjdelcerro
163
        private Map<String,AdditionalResultsPanel> additionalResultsPanels;
164
165
        private static class AdditionalResultsPanel implements Component {
166
167
            private final String name;
168
            private final String title;
169
            private int index;
170
            private final Component component;
171
172
            public AdditionalResultsPanel(String name, String title, Component component, int index) {
173
                this.name = name;
174
                this.title = title;
175
                this.component = component;
176
                this.index = index;
177
            }
178
179
            public AdditionalResultsPanel(String name, String title, Component component) {
180
                this(name, title, component,-1);
181
            }
182
183
            public String getName() {
184
                return this.name;
185
            }
186 44707 jjdelcerro
187 47417 jjdelcerro
            public String getTitle() {
188
                return title;
189
            }
190
191
            public int getIndex() {
192
                return this.index;
193
            }
194
195
            @Override
196
            public JComponent asJComponent() {
197
                return this.component.asJComponent();
198
            }
199
200
            public void setIndex(int index) {
201
                this.index = index;
202
            }
203
204
            public void fireActionEvent(ActionEvent e) {
205
                if( this.component instanceof ActionListenerSupport ) {
206
                    ((ActionListenerSupport)this.component).fireActionEvent(e);
207
                }
208
            }
209
210
            public void doDispose() {
211
                DisposeUtils.dispose(this.component);
212
            }
213
        }
214
215 46063 omartinez
        public static class UseLabelsYesAction extends AbstractAction {
216 44351 jjdelcerro
217 46063 omartinez
                @SuppressWarnings("OverridableMethodCallInConstructor")
218
                public UseLabelsYesAction() {
219
                        I18nManager i18n = ToolsLocator.getI18nManager();
220 44351 jjdelcerro
221 46063 omartinez
                        this.putValue(NAME, i18n.getTranslation("_Use_labels"));
222
                        this.putValue(ACTION_COMMAND_KEY, "UseLabelsYes");
223
                }
224 44351 jjdelcerro
225 46063 omartinez
                @Override
226
                public Object getValue(String key) {
227
                        if (NAME.equals(key)) {
228
                                // Cuando se registra la accion aun no se han cargado las traducciones
229
                                I18nManager i18n = ToolsLocator.getI18nManager();
230
                                return i18n.getTranslation("_Use_labels");
231
                        }
232
                        return super.getValue(key);
233
                }
234 44481 jjdelcerro
235 46063 omartinez
                @Override
236
                public void actionPerformed(ActionEvent ae) {
237 46485 fdiaz
                    DALSwingLocator.getDataSwingManager().setUseLabels(USE_LABELS_YES);
238 46063 omartinez
                }
239
        }
240 44829 omartinez
241 46063 omartinez
        public static class UseLabelsNoAction extends AbstractAction {
242 44351 jjdelcerro
243 46063 omartinez
                @SuppressWarnings("OverridableMethodCallInConstructor")
244
                public UseLabelsNoAction() {
245
                        I18nManager i18n = ToolsLocator.getI18nManager();
246
                        this.putValue(NAME, i18n.getTranslation("_Use_names"));
247
                        this.putValue(ACTION_COMMAND_KEY, "UseLabelsNo");
248
                }
249 44351 jjdelcerro
250 46063 omartinez
                @Override
251
                public Object getValue(String key) {
252
                        if (NAME.equals(key)) {
253
                                // Cuando se registra la accion aun no se han cargado las traducciones
254
                                I18nManager i18n = ToolsLocator.getI18nManager();
255
                                return i18n.getTranslation("_Use_names");
256
                        }
257
                        return super.getValue(key);
258
                }
259 44829 omartinez
260 46063 omartinez
                @Override
261
                public void actionPerformed(ActionEvent ae) {
262 46485 fdiaz
                    DALSwingLocator.getDataSwingManager().setUseLabels(USE_LABELS_NO);
263 46063 omartinez
                }
264
        }
265 44829 omartinez
266 46063 omartinez
        public static class UseLabelsBothAction extends AbstractAction {
267 44351 jjdelcerro
268 46063 omartinez
                @SuppressWarnings("OverridableMethodCallInConstructor")
269
                public UseLabelsBothAction() {
270
                        I18nManager i18n = ToolsLocator.getI18nManager();
271 44351 jjdelcerro
272 46063 omartinez
                        this.putValue(NAME, i18n.getTranslation("_Use_labels_and_names"));
273
                        this.putValue(ACTION_COMMAND_KEY, "UseLabelsBoth");
274
                }
275 44351 jjdelcerro
276 46063 omartinez
                @Override
277
                public Object getValue(String key) {
278
                        if (NAME.equals(key)) {
279
                                // Cuando se registra la accion aun no se han cargado las traducciones
280
                                I18nManager i18n = ToolsLocator.getI18nManager();
281
                                return i18n.getTranslation("_Use_labels_and_names");
282
                        }
283
                        return super.getValue(key);
284
                }
285 44481 jjdelcerro
286 46063 omartinez
                @Override
287
                public void actionPerformed(ActionEvent ae) {
288 46485 fdiaz
                    DALSwingLocator.getDataSwingManager().setUseLabels(USE_LABELS_BOTH);
289 46063 omartinez
                }
290
        }
291 44829 omartinez
292 46063 omartinez
        public static class SelectColumnsAction extends AbstractAction {
293 44644 jjdelcerro
294 46063 omartinez
                @SuppressWarnings("OverridableMethodCallInConstructor")
295
                public SelectColumnsAction() {
296
                        I18nManager i18n = ToolsLocator.getI18nManager();
297 44644 jjdelcerro
298 46063 omartinez
                        this.putValue(NAME, i18n.getTranslation("_Select_columns_to_display"));
299
                        this.putValue(ACTION_COMMAND_KEY, "SelectColumns");
300
                }
301 44644 jjdelcerro
302 46063 omartinez
                @Override
303
                public Object getValue(String key) {
304
                        if (NAME.equals(key)) {
305
                                // Cuando se registra la accion aun no se han cargado las traducciones
306
                                I18nManager i18n = ToolsLocator.getI18nManager();
307
                                return i18n.getTranslation("_Select_columns_to_display");
308
                        }
309
                        return super.getValue(key);
310
                }
311 44644 jjdelcerro
312 46063 omartinez
                @Override
313
                public void actionPerformed(ActionEvent ae) {
314
                        DefaultSearchPanel panel = (DefaultSearchPanel) ae.getSource();
315
                        panel.doSelectResultColumnNames();
316
                }
317
        }
318 44829 omartinez
319 46063 omartinez
        public static class CalculatedColumnsAction extends AbstractAction {
320 44707 jjdelcerro
321 46063 omartinez
                @SuppressWarnings("OverridableMethodCallInConstructor")
322
                public CalculatedColumnsAction() {
323
                        I18nManager i18n = ToolsLocator.getI18nManager();
324 44707 jjdelcerro
325 46063 omartinez
                        this.putValue(NAME, i18n.getTranslation("_Calculated_columns"));
326
                        this.putValue(ACTION_COMMAND_KEY, "CalculatedColumns");
327
                }
328 44707 jjdelcerro
329 46063 omartinez
                @Override
330
                public Object getValue(String key) {
331
                        if (NAME.equals(key)) {
332
                                // Cuando se registra la accion aun no se han cargado las traducciones
333
                                I18nManager i18n = ToolsLocator.getI18nManager();
334
                                return i18n.getTranslation("_Calculated_columns");
335
                        }
336
                        return super.getValue(key);
337
                }
338 44707 jjdelcerro
339 46063 omartinez
                @Override
340
                public void actionPerformed(ActionEvent ae) {
341
                        DefaultSearchPanel panel = (DefaultSearchPanel) ae.getSource();
342
                        panel.doCalculatedColumns();
343
                }
344
        }
345 44829 omartinez
346 46063 omartinez
        public static class GroupByAction extends AbstractAction {
347 44707 jjdelcerro
348 46063 omartinez
                @SuppressWarnings("OverridableMethodCallInConstructor")
349
                public GroupByAction() {
350
                        I18nManager i18n = ToolsLocator.getI18nManager();
351 44707 jjdelcerro
352 46063 omartinez
                        this.putValue(NAME, i18n.getTranslation("_Group_by"));
353
                        this.putValue(ACTION_COMMAND_KEY, "GroupBy");
354
                }
355 44707 jjdelcerro
356 46063 omartinez
                @Override
357
                public Object getValue(String key) {
358
                        if (NAME.equals(key)) {
359
                                // Cuando se registra la accion aun no se han cargado las traducciones
360
                                I18nManager i18n = ToolsLocator.getI18nManager();
361
                                return i18n.getTranslation("_Group_by");
362
                        }
363
                        return super.getValue(key);
364
                }
365 44829 omartinez
366 46063 omartinez
                @Override
367
                public void actionPerformed(ActionEvent ae) {
368
                        DefaultSearchPanel panel = (DefaultSearchPanel) ae.getSource();
369
                        panel.doGroupBy();
370
                }
371
        }
372 44829 omartinez
373 46063 omartinez
        public static class OrderByAction extends AbstractAction {
374 44707 jjdelcerro
375 46063 omartinez
                @SuppressWarnings("OverridableMethodCallInConstructor")
376
                public OrderByAction() {
377
                        I18nManager i18n = ToolsLocator.getI18nManager();
378 44712 jjdelcerro
379 46063 omartinez
                        this.putValue(NAME, i18n.getTranslation("_Order_by"));
380
                        this.putValue(ACTION_COMMAND_KEY, "SelectOrderBy");
381
                }
382 44712 jjdelcerro
383 46063 omartinez
                @Override
384
                public Object getValue(String key) {
385
                        if (NAME.equals(key)) {
386
                                // Cuando se registra la accion aun no se han cargado las traducciones
387
                                I18nManager i18n = ToolsLocator.getI18nManager();
388
                                return i18n.getTranslation("_Order_by");
389
                        }
390
                        return super.getValue(key);
391
                }
392 44712 jjdelcerro
393 46063 omartinez
                @Override
394
                public void actionPerformed(ActionEvent ae) {
395
                        DefaultSearchPanel panel = (DefaultSearchPanel) ae.getSource();
396
                        panel.doOrderBy();
397
                }
398
        }
399 44829 omartinez
400 46536 fdiaz
        public static class PropertiesAction extends AbstractAction {
401
402
                @SuppressWarnings("OverridableMethodCallInConstructor")
403
                public PropertiesAction() {
404
                        I18nManager i18n = ToolsLocator.getI18nManager();
405
406
                        this.putValue(NAME, i18n.getTranslation("_Properties"));
407
                        this.putValue(ACTION_COMMAND_KEY, "Properties");
408
                }
409
410
                @Override
411
                public Object getValue(String key) {
412
                        if (NAME.equals(key)) {
413
                                // Cuando se registra la accion aun no se han cargado las traducciones
414
                                I18nManager i18n = ToolsLocator.getI18nManager();
415
                                return i18n.getTranslation("_Properties");
416
                        }
417
                        return super.getValue(key);
418
                }
419
420
                @Override
421
                public void actionPerformed(ActionEvent ae) {
422
                        DefaultSearchPanel panel = (DefaultSearchPanel) ae.getSource();
423
                        panel.doShowProperties();
424
                }
425
        }
426
427 46063 omartinez
        private class TablePopupMenu extends JPopupMenu {
428 44829 omartinez
429 46063 omartinez
                public final JTable table;
430 44259 jjdelcerro
431 46063 omartinez
                @SuppressWarnings("OverridableMethodCallInConstructor")
432
                public TablePopupMenu(JTable inputTable) {
433
                        this.table = inputTable;
434
                        I18nManager i18n = ToolsLocator.getI18nManager();
435
                        JMenuItem copyRowsActionMenu = new JMenuItem(i18n.getTranslation("_Copy_rows"));
436
                        copyRowsActionMenu.addActionListener((ActionEvent e) -> {
437
                                doCopyRows(table);
438
                        });
439
                        this.add(copyRowsActionMenu);
440 47228 fdiaz
                        JMenuItem exportTSVActionMenu = new JMenuItem(i18n.getTranslation(EXPORT_TO_TSV_TITLE));
441 46585 fdiaz
                        exportTSVActionMenu.addActionListener((ActionEvent e) -> {
442
                                doExportTSV(table);
443
                        });
444
                        this.add(exportTSVActionMenu);
445 46063 omartinez
                }
446
        }
447 44281 jjdelcerro
448 46063 omartinez
        private class ActionButtons {
449 44829 omartinez
450 46063 omartinez
                private final DALActionFactory factory;
451
                private final Action action;
452
                private final JButton button;
453 44829 omartinez
454 46063 omartinez
                public ActionButtons(DALActionFactory factory, Action action, JButton button) {
455
                        this.factory = factory;
456
                        this.action = action;
457
                        this.button = button;
458
                }
459
        }
460
461
        public static class SearchActionContext extends AbstractDALActionContext {
462
463
                private final DefaultSearchPanel panel;
464
465
                public SearchActionContext(DefaultSearchPanel panel) {
466
                        super(FeatureStoreSearchPanel.ACTION_CONTEXT_NAME);
467
                        this.panel = panel;
468
                }
469
470
                @Override
471
                public DataStore getStore() {
472 47417 jjdelcerro
                        if (this.panel.currentPostProcess != null && this.panel.tabResults.getSelectedIndex() == 1) {
473
                                return this.panel.postProcessStore;
474
                        } else {
475 46063 omartinez
                                return this.panel.getStore();
476
                        }
477
                }
478 44281 jjdelcerro
479 46063 omartinez
                @Override
480
                public JComponent getActionButton(String actionName) {
481
                        return this.panel.getActionButton(actionName);
482
                }
483 44829 omartinez
484 46063 omartinez
                @Override
485
                public int getSelectedsCount() {
486
                        return this.panel.getSelectedFeatureCount();
487
                }
488 44829 omartinez
489 46063 omartinez
                @Override
490
                public Expression getFilterForSelecteds() {
491 46900 jjdelcerro
                        return this.panel.getFilterForSelectedFeatures();
492 46063 omartinez
                }
493 44829 omartinez
494 46900 jjdelcerro
                @Override
495
                public FeatureSelection getSelecteds() {
496
                        return this.panel.getSelectedFeatures();
497
                }
498
499 46063 omartinez
                @Override
500
                public FeatureQuery getQuery() {
501 47417 jjdelcerro
                        if (this.panel.currentPostProcess != null && this.panel.tabResults.getSelectedIndex() == 1) {
502
                            return this.panel.postProcessQuery;
503
                        } else {
504 46587 jjdelcerro
                            SearchParameters searchParams = this.panel.parameters;
505 46594 jjdelcerro
                            FeatureQuery query = searchParams.getQueryToApply();
506 47184 jjdelcerro
                            if( panel.useSelection() ) {
507
                                query = panel.addSelection(panel.store, query);
508
                            }
509 46587 jjdelcerro
                            return query;
510 46063 omartinez
                        }
511
                }
512
        }
513 44829 omartinez
514 46063 omartinez
        private FeatureStore store;
515
        private final ActionListenerSupport acctionListeners;
516
        private final Map<String, ActionButtons> actions;
517
        private boolean showActions = true;
518
        private DefaultSearchParameters parameters;
519 45537 jolivas
520 46063 omartinez
        private List<SearchConditionPanel> conditionPanels;
521 44259 jjdelcerro
522 46063 omartinez
        public static final int PANEL_SIMPLIFIED = 0;
523
        public static final int PANEL_ADVANCED = 1;
524
        private static final String BOOKMARKSANDHISTORY_NAME = "SearchPanel";
525
        private final Bookmarks<Object> bookmarks;
526
        private final History<Object> history;
527
        private boolean filterOnlyMode;
528 44829 omartinez
529 46063 omartinez
        private String currentPostProcess;
530 44829 omartinez
531 46063 omartinez
        private DynObject postProcessParams;
532
        private FeatureStore postProcessStore;
533
        private FeatureQuery postProcessQuery;
534
        private SimpleFeaturesTableModel resultModel;
535
        private SimpleFeaturesTableModel resultPostProcessModel;
536 45537 jolivas
537 46063 omartinez
        private boolean processing;
538
        private JComponent configurableActions;
539 45537 jolivas
540 46063 omartinez
        @SuppressWarnings({"OverridableMethodCallInConstructor", "LeakingThisInConstructor"})
541
        public DefaultSearchPanel(FeatureStore store) {
542
                this.store = store;
543
                this.filterOnlyMode = false;
544
                DisposeUtils.bind(store);
545
                this.acctionListeners = ToolsSwingLocator.getToolsSwingManager().createActionListenerSupport();
546
                this.actions = new HashMap<>();
547
                this.parameters = new DefaultSearchParameters();
548 47417 jjdelcerro
                this.additionalResultsPanels = new HashMap<>();
549 46063 omartinez
                FeatureQuery featureQuery = this.store.createFeatureQuery();
550
                featureQuery.retrievesAllAttributes();
551
                this.parameters.setQuery(featureQuery);
552
                this.currentPostProcess = null;
553
                this.postProcessParams = null;
554
                this.postProcessStore = null;
555
                this.postProcessQuery = null;
556
                this.processing = false;
557
                this.configurableActions = null;
558
                this.resultModel = null;
559
                this.resultPostProcessModel = null;
560
                this.propertiesHelper = new PropertiesSupportHelper();
561
                this.propertiesHelper.setProperty("SearchPanel", this);
562 46485 fdiaz
                this.automaticallySearch = true;
563 46665 jjdelcerro
                this.postProcessEnabled = true;
564
                this.groupByEnabled = true;
565 45537 jolivas
566 46063 omartinez
                Search search = (Search) ToolsLocator.getComplementsManager().get(
567
                        Search.COMPLEMENT_MANE, getFeatureType()
568
                );
569
                List<Search.OrderedAttribute> attributos = search.getOrderedAttributes(
570
                        Search.BASIC_TYPES_FILTER,
571
                        Search.STR_INT_LONG_LABEL_ORDER,
572
                        12
573
                );
574
                for (Search.OrderedAttribute attrdesc : attributos) {
575
                        this.parameters.getResultColumnNames().add(attrdesc.getDescriptor().getName());
576
                }
577
                this.bookmarks = ToolsLocator.getBookmarksAndHistoryManager().getBookmarksGroup(BOOKMARKSANDHISTORY_NAME);
578
                this.history = ToolsLocator.getBookmarksAndHistoryManager().getHistoryGroup(BOOKMARKSANDHISTORY_NAME);
579 46505 fdiaz
                this.initComponents0();
580
                this.initialized = false;
581 46063 omartinez
        }
582 44829 omartinez
583 46063 omartinez
        @Override
584
        public void dispose() {
585
                DisposeUtils.disposeQuietly(store);
586
                TableModel m = this.tblResults.getModel();
587
                if (m instanceof Disposable) {
588
                        DisposeUtils.disposeQuietly((Disposable) m);
589
                }
590
                this.store = null;
591
                this.tblResults.setModel(new DefaultTableModel());
592 47417 jjdelcerro
                for (AdditionalResultsPanel additionalResultsPanel : this.additionalResultsPanels.values()) {
593
                    additionalResultsPanel.doDispose();
594
                }
595 46063 omartinez
        }
596 44259 jjdelcerro
597 46063 omartinez
        @Override
598
        public JComponent asJComponent() {
599 46505 fdiaz
                if (!this.initialized) { //this.conditionPanels == null) {
600
                        this.initComponents1();
601 46063 omartinez
                }
602
                return this;
603
        }
604 45100 jjdelcerro
605 46063 omartinez
        private void addActions() {
606
                if (!this.showActions) {
607
                        return;
608
                }
609
                this.pnlActions.removeAll();
610
                this.pnlActions.setLayout(new FlowLayout(FlowLayout.TRAILING, 8, 4));
611
                SearchActionContext actionContext = new SearchActionContext(this);
612 46849 jjdelcerro
                actionContext.set("searchpanel", this);
613
                Collection<DALActionFactory> factories = DALSwingLocator.getSwingManager().getApplicableStoreActions(actionContext);
614 46063 omartinez
                for (DALActionFactory factory : factories) {
615 46849 jjdelcerro
                    Action action = factory.createAction(actionContext);
616
                    JButton button = new JButton(action);
617
                    this.actions.put(factory.getName(), new ActionButtons(factory, action, button));
618
                    button.setBorder(BorderFactory.createEmptyBorder());
619
                    button.setBorderPainted(false);
620
                    button.setFocusPainted(false);
621
                    button.setContentAreaFilled(false);
622
                    button.setCursor(new Cursor(Cursor.HAND_CURSOR));
623
                    this.pnlActions.add(button);
624 46063 omartinez
                }
625
                this.pnlActions.revalidate();
626
                this.pnlActions.repaint();
627
        }
628 44259 jjdelcerro
629 46063 omartinez
        @Override
630
        public void addActionListener(ActionListener listener) {
631
                this.acctionListeners.addActionListener(listener);
632
        }
633 44263 jjdelcerro
634 46063 omartinez
        @Override
635
        public ActionListener[] getActionListeners() {
636
                return this.acctionListeners.getActionListeners();
637
        }
638 44259 jjdelcerro
639 46063 omartinez
        @Override
640
        public void removeActionListener(ActionListener listener) {
641
                this.acctionListeners.removeActionListener(listener);
642
        }
643 44259 jjdelcerro
644 46063 omartinez
        @Override
645
        public void removeAllActionListener() {
646
                this.acctionListeners.removeAllActionListener();
647
        }
648 44259 jjdelcerro
649 46063 omartinez
        @Override
650
        public void fireActionEvent(ActionEvent event) {
651
                this.acctionListeners.fireActionEvent(event);
652
        }
653 44259 jjdelcerro
654 46063 omartinez
        @Override
655
        public boolean hasActionListeners() {
656
                return this.acctionListeners.hasActionListeners();
657
        }
658 44259 jjdelcerro
659 46505 fdiaz
        private void initComponents0() {
660 46063 omartinez
                this.conditionPanels = new ArrayList<>();
661 46505 fdiaz
                this.taskStatusController = ToolsSwingLocator.getTaskStatusSwingManager().createTaskStatusController(
662
                        this.lblStatusTitle,
663
                        this.lblMsg,
664
                        this.pgbStatus);
665
        }
666 44259 jjdelcerro
667 46505 fdiaz
        private void initComponents1() {
668
669 46063 omartinez
                ToolsSwingManager swingManager = ToolsSwingLocator.getToolsSwingManager();
670
                swingManager.translate(this.tabSearchMode);
671
                swingManager.translate(this.tabResults);
672
                swingManager.translate(this.btnSearch);
673
                swingManager.translate(this.btnClear);
674
                swingManager.translate(this.btnSearchPostProcess);
675
                swingManager.translate(this.lblExpressionDeBusqueda);
676
                swingManager.translate(this.btnAddAccumulatedFilter);
677
                swingManager.translate(this.btnRemoveAccumulatedFilter);
678
                swingManager.translate(this.btnViewAccumulatedFilter);
679 47184 jjdelcerro
                swingManager.translate(this.chkUseSelection);
680 44707 jjdelcerro
681 46063 omartinez
                ConfigurableActionsMamager cfgActionsManager = ToolsUtilLocator.getConfigurableActionsMamager();
682
                this.configurableActions = cfgActionsManager.getConfigurableActionsComponent(CONFIGURABLE_PANEL_ID, this);
683
                this.pnlCfgActions.setLayout(new BorderLayout(0, 0));
684
                this.pnlCfgActions.add(configurableActions, BorderLayout.CENTER);
685
686 46062 omartinez
                this.pgbStatus.setVisible(false);
687 44829 omartinez
688 46063 omartinez
                this.conditionPanels.add(
689
                        new SearchConditionPanelSimplified(
690
                                parameters,
691
                                store,
692 47264 jjdelcerro
                                this.pnlConditionField,
693 46063 omartinez
                                btnAddAccumulatedFilter,
694
                                btnRemoveAccumulatedFilter,
695 47264 jjdelcerro
                                btnViewAccumulatedFilter
696 46063 omartinez
                        )
697
                );
698 44829 omartinez
699 46063 omartinez
                SearchConditionPanelAdvanced advancedPanel = new SearchConditionPanelAdvanced(
700
                        this.store,
701
                        txtAdvancedExpression,
702
                        btnAdvancedExpression,
703
                        btnAdvancedExpressionHistory,
704
                        btnAdvancedExpressionBookmarks
705
                );
706
                this.conditionPanels.add(advancedPanel);
707 44259 jjdelcerro
708 46063 omartinez
                for (SearchConditionPanelFactory factory : DALSwingLocator.getManager().getSearchConditionPanels()) {
709
                        String factoryName = "unknown";
710
                        try {
711
                                factoryName = factory.getName();
712
                                if (factory.isApplicable(store)) {
713
                                        SearchConditionPanel panel = factory.create(this);
714
                                        this.conditionPanels.add(panel);
715
                                        this.tabSearchMode.add(factory.getName(), panel.asJComponent());
716
                                }
717
                        } catch (Throwable th) {
718 47417 jjdelcerro
                                LOGGER.warn("Can't create search panel '" + factoryName + "'.", th);
719 46063 omartinez
                        }
720
                }
721 44829 omartinez
722 46063 omartinez
                this.btnSearch.addActionListener((ActionEvent e) -> {
723
                        this.tabResults.setEnabledAt(1, false);
724
                        search();
725
                });
726 44822 jjdelcerro
727 46063 omartinez
                this.tblResults.getSelectionModel().addListSelectionListener((ListSelectionEvent e) -> {
728
                        try {
729
                                lastSelectedFeature = resultModel.getFeatureAt(tblResults.getSelectedRow());
730
                        } catch (Throwable th) {
731
                                LOGGER.debug("Can't retrieve last selected feature.", th);
732
                        }
733
                        for (ActionButtons actionButton : actions.values()) {
734
                                if (actionButton.action instanceof ListSelectionListener) {
735
                                        ((ListSelectionListener) actionButton.action).valueChanged(e);
736
                                }
737
                        }
738
                });
739
                this.btnClear.addActionListener((ActionEvent e) -> {
740
                        clear();
741
                });
742
                addActions();
743
744
                //swingManager.createTableColumnAdjuster(tblResults);
745
                //swingManager.createTableColumnAdjuster(tblSearchPostProcessResults);
746 45794 jjdelcerro
//        this.setPreferredSize(new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT));
747 46063 omartinez
                ToolsSwingUtils.ensureRowsCols(this, 20, 100, 30, 120);
748 44259 jjdelcerro
749 46063 omartinez
                this.bookmarksController = ToolsSwingLocator.getToolsSwingManager().createBookmarksController(this.bookmarks, btnBookmarks);
750
                this.historyController = ToolsSwingLocator.getToolsSwingManager().createHistoryController(this.history, btnHistory);
751 44829 omartinez
752 46063 omartinez
                this.historyController.setFilter(null);
753 44829 omartinez
754 46463 fdiaz
                this.historyController.addActionListener((ActionEvent e) -> {
755 46063 omartinez
                        ActionEventWithCurrentValue<DefaultSearchParameters> b = (ActionEventWithCurrentValue<DefaultSearchParameters>) e;
756
                        switch (b.getID()) {
757
                                case ID_GETVALUE:
758
                                        DefaultSearchParameters actualParams = (DefaultSearchParameters) fetch(null);
759
                                        b.setCurrentValue(actualParams);
760
                                        break;
761 45537 jolivas
762 46063 omartinez
                                case ID_SETVALUE:
763
                                        if (b.getCurrentValue() == null) {
764
                                                return;
765
                                        }
766 46485 fdiaz
                                        putParametersAndSearch(b.getCurrentValue());
767 46463 fdiaz
                                        break;
768
                        }
769
                });
770
                this.bookmarksController.addActionListener((ActionEvent e) -> {
771
                        BookmarkEvent<DefaultSearchParameters> b = (BookmarkEvent<DefaultSearchParameters>) e;
772
                        switch (b.getID()) {
773
                                case ID_GETVALUE:
774 46585 fdiaz
                                    LOGGER.info("Save bookmark");
775 46463 fdiaz
                                        DefaultSearchParameters actualParams = (DefaultSearchParameters) fetch(null);
776
                                        b.setCurrentValue(actualParams);
777
                                        break;
778
779
                                case ID_SETVALUE:
780 46585 fdiaz
                                    LOGGER.info("Restore bookmark");
781 46463 fdiaz
                                        if (b.getCurrentValue() == null) {
782 46063 omartinez
                                                return;
783
                                        }
784 46463 fdiaz
                                        b.getBookmark().used();
785 46536 fdiaz
                                        b.getCurrentValue().setName(b.getBookmark().getName());
786 46485 fdiaz
                                        putParametersAndSearch(b.getCurrentValue());
787 46063 omartinez
                                        break;
788 46536 fdiaz
                                case ID_SETNAME:
789 46585 fdiaz
                                    LOGGER.info("Rename bookmark");
790 46536 fdiaz
                                        if (b.getCurrentValue() == null) {
791
                                                return;
792
                                        }
793
                                        b.getCurrentValue().setName(b.getBookmark().getName());
794
                                        break;
795 46063 omartinez
                        }
796 46463 fdiaz
                });
797 46063 omartinez
                this.addComponentListener(new ComponentAdapter() {
798
                        @Override
799
                        public void componentHidden(ComponentEvent e) {
800
                                dispose();
801
                        }
802
                });
803 45537 jolivas
804 46063 omartinez
                this.btnSearchPostProcess.addActionListener((ActionEvent e) -> {
805
                        try {
806
                                doSelectSearchPostprocess();
807
                        } catch (DataException ex) {
808
                                LOGGER.warn("Can't select a Search Post Process", ex);
809
                        }
810
                });
811 45537 jolivas
812 46063 omartinez
                this.tabResults.setEnabledAt(1, false);
813
                this.tblResults.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
814
                this.tblResults.addKeyListener(new KeyAdapter() {
815
                        @Override
816
                        public void keyPressed(KeyEvent e) {
817
                                if (e.getKeyCode() == KeyEvent.VK_F4) {
818
                                        doShowCellInDialog();
819
                                }
820
                        }
821
                });
822
                this.tblResults.setComponentPopupMenu(new TablePopupMenu(this.tblResults));
823
                this.tabResults.addChangeListener((ChangeEvent evt) -> {
824
                        SwingUtilities.invokeLater(() -> {
825 47417 jjdelcerro
                                switch(tabResults.getSelectedIndex()) {
826
                                    case 1:
827
                                        updateNumberElementsMsg(resultPostProcessModel);
828
                                        break;
829
                                    case 0:
830
                                    default:
831 46063 omartinez
                                        updateNumberElementsMsg(resultModel);
832
                                }
833
                        });
834
                });
835 46849 jjdelcerro
                this.tblResults.getTableHeader().setReorderingAllowed(false);
836
837
                this.tblSearchPostProcessResults.setComponentPopupMenu(new TablePopupMenu(this.tblSearchPostProcessResults));
838
                this.tblSearchPostProcessResults.getTableHeader().setReorderingAllowed(false);
839
840
                if (this.filterOnlyMode || !this.postProcessEnabled) {
841 46063 omartinez
                        this.btnSearchPostProcess.setVisible(false);
842
                }
843 47417 jjdelcerro
844
                for (SearchResultsPanelFactory factory : DALSwingLocator.getManager().getSearchResultsPanels()) {
845
                        String factoryName = "unknown";
846
                        try {
847
                            factoryName = factory.getName();
848
                            this.addResultPanel(
849
                                    factory.getName(),
850
                                    factory.getTitle(),
851
                                    factory.create(this)
852
                                );
853
                        } catch (Throwable th) {
854
                                LOGGER.warn("Can't create results panel '" + factoryName + "'.",th);
855
                        }
856
                }
857
                for (AdditionalResultsPanel panel : this.additionalResultsPanels.values()) {
858
                    panel.setIndex(this.tabResults.getTabCount());
859
                    this.tabResults.addTab(panel.getTitle(), panel.asJComponent());
860
                }
861 46463 fdiaz
862 46505 fdiaz
                this.initialized = true;
863
864 46485 fdiaz
                if (this.automaticallySearch){
865
                    if (this.bookmarks.hasBookmark(this.store.getName())) {
866
                            Bookmark<DefaultSearchParameters> initBookmark = this.bookmarks.get(this.store.getName());
867
                            initBookmark.used();
868
                            putParametersAndSearch(initBookmark.getValue());
869
                    } else {
870
                        clear();
871
                        search();
872
                    }
873
                } else {
874 46463 fdiaz
                    clear();
875 46485 fdiaz
876 46463 fdiaz
                }
877 46063 omartinez
        }
878 46463 fdiaz
879 46485 fdiaz
    private void putParametersAndSearch(DefaultSearchParameters searchParams) {
880 46463 fdiaz
        DefaultSearchParameters params;
881
        try {
882
            params = searchParams.getCopy();
883 46505 fdiaz
            FeatureType featType = this.getFeatureType();
884
            StringBuilder errMessage = new StringBuilder();
885
            boolean onlyEssentials = false;
886
            boolean isValid = params.isValid(featType, errMessage);
887
            if(!isValid){
888
                ThreadSafeDialogsManager dialogs = ToolsSwingLocator.getThreadSafeDialogsManager();
889
                I18nManager i18n = ToolsLocator.getI18nManager();
890
                int n = dialogs.confirmDialog(
891
                        i18n.getTranslation("_The_validation_of_the_search_parameters_has_returned_the_following_errors")+":\n\n"+errMessage.toString()+"\n"+i18n.getTranslation("_You_want_the_application_to_try_to_resolve_them_before_launching_the_query"),
892
                        i18n.getTranslation("_Validation_of_search_parameters"),
893
                        JOptionPane.YES_NO_OPTION,
894
                        JOptionPane.WARNING_MESSAGE,
895
                        "_Fix_search_parameters"
896
                );
897
                if( n != JOptionPane.YES_OPTION ) {
898
                    onlyEssentials = true;
899 46585 fdiaz
                } else {
900
                    LOGGER.info("It has been decided do not resolve errors in parameters of search");
901 46505 fdiaz
                }
902
903
            }
904
            params.fix(featType, onlyEssentials);
905 46463 fdiaz
        } catch (Exception ex) {
906
            LOGGER.warn("Not been able to clone export parameters", ex);
907
            return;
908
        }
909
        clear();
910
        put(params);
911
        Thread th = new Thread(() -> {
912
            doSearch(params);
913
        });
914
        th.start();
915 45247 omartinez
916 46463 fdiaz
    }
917
918 46063 omartinez
        private void doShowCellInDialog() {
919
                int row = this.tblResults.getSelectedRow();
920
                if (row < 0) {
921
                        return;
922
                }
923
                int col = this.tblResults.getSelectedColumn();
924
                if (col < 0) {
925
                        return;
926
                }
927
                String s = Objects.toString(this.tblResults.getValueAt(row, col), null);
928
                if (StringUtils.isBlank(s)) {
929
                        return;
930
                }
931
                ToolsSwingLocator.getToolsSwingManager().showZoomDialog(
932
                        this,
933
                        this.tblResults.getColumnName(col),
934
                        s,
935
                        false
936
                );
937
        }
938 44262 jjdelcerro
939 46063 omartinez
        @Override
940
        public FeatureType getFeatureType() {
941
                try {
942
                        return store.getDefaultFeatureType();
943
                } catch (Exception ex) {
944
                        throw new RuntimeException("Can't retrieve the feature type.", ex);
945
                }
946
        }
947 44259 jjdelcerro
948 46063 omartinez
        @Override
949
        public void setEnabled(boolean enabled) {
950
                if (!SwingUtilities.isEventDispatchThread()) {
951
                        SwingUtilities.invokeLater(() -> {
952
                                setEnabled(enabled);
953
                        });
954
                        return;
955
                }
956
957 46505 fdiaz
                if (!this.initialized) { //this.conditionPanels == null) {
958
                        this.initComponents1();
959 46063 omartinez
                }
960
                for (SearchConditionPanel conditionPanel : conditionPanels) {
961
                        conditionPanel.setEnabled(enabled);
962
                }
963
964
                this.btnClear.setEnabled(enabled);
965
                this.btnSearch.setEnabled(enabled);
966
                for (ActionButtons actionButton : actions.values()) {
967
                        actionButton.action.setEnabled(enabled);
968
                }
969
                this.btnSearchPostProcess.setEnabled(enabled);
970
                //bookmarkController,historyController,configurableActions
971
        }
972
973
        @Override
974
        public void clear() {
975
                this.taskStatusController.setTitle("");
976 46505 fdiaz
                if (!this.initialized) { //this.conditionPanels == null) {
977 46063 omartinez
                        return;
978
                }
979
                for (SearchConditionPanel conditionPanel : conditionPanels) {
980
                        conditionPanel.clear();
981
                }
982
                FeatureQuery emptyQuery = this.store.createFeatureQuery();
983
                emptyQuery.retrievesAllAttributes();
984
                this.parameters.setQuery(emptyQuery);
985
                // Mantener las columnas visualizadas
986
                // Elimina las que no existen en el store como campos calculados que
987
                // pudieran existir en el fquery
988
                List<String> resultColumnNames = this.parameters.getResultColumnNames();
989
                ArrayList<String> toDeleteAlreadyDontExist = new ArrayList<>();
990
                for (String resultColumnName : resultColumnNames) {
991
                        try {
992
                                FeatureAttributeDescriptor attr = this.store.getDefaultFeatureType().getAttributeDescriptor(resultColumnName);
993
                                if (attr == null) {
994
                                        toDeleteAlreadyDontExist.add(resultColumnName);
995
                                }
996
                        } catch (DataException ex) {
997
998
                        }
999
                }
1000
                resultColumnNames.removeAll(toDeleteAlreadyDontExist);
1001
                resetTable();
1002
        }
1003
1004
        @Override
1005
        public FeatureQuery getLastQuery() {
1006
                return this.lastQuery;
1007
        }
1008
1009
        public boolean isValid(StringBuilder message) {
1010
                int searchMode = this.tabSearchMode.getSelectedIndex();
1011
                SearchConditionPanel panel = this.conditionPanels.get(searchMode);
1012
                boolean valid = panel.isValid(message);
1013
                return valid;
1014
        }
1015
1016 47275 jjdelcerro
        public String getWarnings() {
1017
                int searchMode = this.tabSearchMode.getSelectedIndex();
1018
                SearchConditionPanel panel = this.conditionPanels.get(searchMode);
1019
                String s = panel.getWarnings();
1020
                if( StringUtils.isBlank(s) ) {
1021
                    return null;
1022
                }
1023
                return s;
1024
        }
1025
1026 46063 omartinez
        @Override
1027 46482 jjdelcerro
        public int search() {
1028 46063 omartinez
                StringBuilder message = new StringBuilder();
1029
                if (!this.isValid(message)) {
1030
                        ThreadSafeDialogsManager dialogManager = ToolsSwingLocator.getThreadSafeDialogsManager();
1031
                        dialogManager.messageDialog(
1032
                                "_The_specified_search_condition_is_not_valid",
1033
                                "_Search",
1034
                                JOptionPane.WARNING_MESSAGE
1035
                        );
1036 46482 jjdelcerro
                        return STATUS_NOT_VALID;
1037 46063 omartinez
                }
1038 47275 jjdelcerro
                String warnings = this.getWarnings();
1039
                if( StringUtils.isNotBlank(warnings) ) {
1040
                        ThreadSafeDialogsManager dialogManager = ToolsSwingLocator.getThreadSafeDialogsManager();
1041
                        int n = dialogManager.confirmDialog(
1042
                                "The indicated search can cause problems." +
1043
                                        "\n" + warnings + "\n" +
1044
                                        "Do you want to run it anyway?",
1045
                                "_Search",
1046
                                JOptionPane.YES_NO_OPTION,
1047
                                JOptionPane.WARNING_MESSAGE
1048
                        );
1049
                        if( n == JOptionPane.NO_OPTION ) {
1050
                            return STATUS_OK;
1051
                        }
1052
                }
1053 46063 omartinez
                lblMsg.setText(ToolsLocator.getI18nManager().getTranslation("_Searching") + "...");
1054
                setEnabled(false);
1055
                Thread th = new Thread(() -> {
1056
                        try {
1057 46062 omartinez
                                SearchParameters searchParams;
1058
                                try {
1059
                                        searchParams = this.fetch(this.parameters.getCopy()); // esto lo actualiza a la ultima // decidir si se devuelve clonado
1060 45537 jolivas
1061 46062 omartinez
                                        Date date = Calendar.getInstance().getTime();
1062
                                        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
1063
                                        String strDate = dateFormat.format(date);
1064
                                        searchParams.setName("Params: " + strDate);
1065
                                } catch (Exception ex) {
1066
                                        LOGGER.warn("Not able to create search parameters.", ex);
1067
                                        this.taskStatusController.setTitle(ToolsLocator.getI18nManager().getTranslation("_Errors_fetching_new_query") + "...");
1068
                                        resetTable();
1069
                                        return;
1070
                                }
1071
                                doSearch(searchParams);
1072
                        } catch (Exception ex) {
1073
                                LOGGER.warn("Search panel has errors during the search", ex);
1074
                                resetTable();
1075
                        } finally {
1076
                                SwingUtilities.invokeLater(() -> {
1077
                                        setEnabled(true);
1078
                                });
1079
                        }
1080 46063 omartinez
                });
1081
                th.start();
1082 46482 jjdelcerro
                return STATUS_OK;
1083 46063 omartinez
        }
1084
1085 46485 fdiaz
        @Override
1086 46482 jjdelcerro
        public int search(SearchParameters searchParams) {
1087 46485 fdiaz
            ((DefaultSearchParameters)searchParams).fix(this.getFeatureType());
1088
            return doSearch(searchParams);
1089 46482 jjdelcerro
        }
1090
1091 47274 jjdelcerro
        private synchronized int doSearch(SearchParameters searchParams) {
1092 46063 omartinez
                final MutableObject model = new MutableObject(null);
1093
                final MutableLong rowCount = new MutableLong();
1094
                Cursor savedCursor = this.getCursor();
1095
                SimpleTaskStatus status = ToolsLocator.getTaskStatusManager().createDefaultSimpleTaskStatus("");
1096
                status.setAutoremove(true);
1097
                status.add();
1098
                this.taskStatusController.bind(status);
1099 46517 fdiaz
                List<Feature> features = null;
1100 46063 omartinez
                try {
1101 46585 fdiaz
                    LOGGER.info("Do search");
1102 46063 omartinez
                        status.setTitle(ToolsLocator.getI18nManager().getTranslation("_Processing_search"));
1103
                        SwingUtilities.invokeLater(() -> {
1104 46505 fdiaz
                            if(this.initialized){
1105 46063 omartinez
                                this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
1106 46505 fdiaz
                            }
1107 46063 omartinez
                        });
1108
                        List<String> resultColumnNames = searchParams.getResultColumnNames();
1109 46594 jjdelcerro
                        FeatureQuery myQuery = searchParams.getQueryToApply();
1110 47184 jjdelcerro
                        if( this.useSelection() ) {
1111
                            myQuery = this.addSelection(this.store, myQuery);
1112
                        }
1113 46063 omartinez
                        features = store.getFeatures(myQuery, 50);
1114
                        FacadeOfAFeaturePagingHelper facade = (FacadeOfAFeaturePagingHelper) features;
1115
                        FeatureType ftype = facade.getFeaturePagingHelper().getFeatureSet().getDefaultFeatureType();
1116
                        // al modelo le pasamos el ftype de esas features
1117
                        SimpleFeaturesTableModel tableModel = new SimpleFeaturesTableModelImpl(
1118
                                ftype,
1119
                                resultColumnNames,
1120
                                features
1121
                        );
1122
                        model.setValue(tableModel);
1123 46517 fdiaz
                        rowCount.setValue(features.size());
1124
                        if(rowCount.longValue() > 0){
1125
                            //Force to get first row in this thread
1126
                            Feature f = features.get(0);
1127
                        }
1128 46485 fdiaz
                        resultModel = (SimpleFeaturesTableModel) model.getValue();
1129 46063 omartinez
                        SwingUtilities.invokeLater(() -> {
1130 46505 fdiaz
                            if(this.initialized){
1131 46063 omartinez
                                I18nManager i18n = ToolsLocator.getI18nManager();
1132
                                try {
1133 47417 jjdelcerro
                                        if( this.tabResults.getSelectedIndex()==1 ) {
1134
                                            this.tabResults.setSelectedIndex(0);
1135
                                        }
1136 46063 omartinez
                                        TableModel oldmodel = tblResults.getModel();
1137
                                        tblResults.setModel(resultModel);
1138
                                        resultModel.setCellRenderers(tblResults, getCustomRenderers(searchParams));
1139
                                        if (oldmodel instanceof SimpleFeaturesTableModelImpl) {
1140
                                                ((SimpleFeaturesTableModelImpl) oldmodel).dispose();
1141
                                        }
1142
                                        if (resultModel.hasErrors()) {
1143
                                                status.setTitle(i18n.getTranslation("_Errors_occurred_during_search"));
1144
                                        } else {
1145
                                                status.setTitle(String.format("%d " + i18n.getTranslation("_elements"), rowCount.getValue()));
1146
                                        }
1147
                                        if (this.parameters != null && this.parameters.getQuery() != null) {
1148
                                                this.history.add(searchParams);
1149
                                        }
1150 47417 jjdelcerro
                                        this.fireSearchEvent();
1151 46063 omartinez
                                } catch (Exception ex) {
1152
                                        LOGGER.warn(" Errors occurred during search getting old model", ex);
1153
                                        status.setTitle(i18n.getTranslation("_Errors_occurred_during_search"));
1154
                                } finally {
1155
                                        setEnabled(true);
1156
                                        status.terminate();
1157
                                        this.setCursor(savedCursor);
1158
                                }
1159 46505 fdiaz
                            }
1160 46063 omartinez
                        });
1161 46517 fdiaz
1162
                } catch (Exception ex) {
1163
                        LOGGER.warn("Search not able to be executed. Can't get features or create table model", ex);
1164
                        status.setTitle(ToolsLocator.getI18nManager().getTranslation("_Errors_getting_new_feature_set") + "...");
1165
                        status.abort();
1166
                        DisposeUtils.disposeQuietly(features);
1167
                        this.lastErrorMessage = this.getLastErrorMessage(ex);
1168
                        if(StringUtils.isNotBlank(this.lastErrorMessage)){
1169
                            status.setTitle(this.lastErrorMessage);
1170
                        }
1171
                        resetTable();
1172
                        return STATUS_ERROR1;
1173 46063 omartinez
                }
1174 46482 jjdelcerro
                return STATUS_OK;
1175 46063 omartinez
        }
1176
1177 46482 jjdelcerro
        @Override
1178
        public SimpleFeaturesTableModel getResultsTableModel() {
1179
            return this.resultModel;
1180
        }
1181
1182 46063 omartinez
        private Map<String, TableCellRenderer> getCustomRenderers(SearchParameters parameters) {
1183
                FeatureType ft = this.store.getDefaultFeatureTypeQuietly();
1184 47184 jjdelcerro
                HashMap<String, TableCellRenderer> renderers = new HashMap<>();
1185 46063 omartinez
                for (FeatureAttributeDescriptor attr : ft) {
1186
                        if (attr.getDataType().isNumeric()) {
1187 46051 omartinez
//                renderers.put(attr.getName(), new ColorRangeRenderer(attr, 20, 50));
1188 46063 omartinez
                        }
1189
                }
1190
                return renderers;
1191
        }
1192 45280 omartinez
1193 46063 omartinez
        private void resetTable() {
1194
                if (!SwingUtilities.isEventDispatchThread()) {
1195 46505 fdiaz
                        SwingUtilities.invokeLater(() -> {
1196
                            if(this.initialized){
1197
                                resetTable();
1198
                            }
1199
                        });
1200 46063 omartinez
                        return;
1201
                }
1202
                List<String> resultColumnNames = null;
1203
                try {
1204
                        resultColumnNames = this.parameters.getResultColumnNames();
1205
                } catch (Exception ex) {
1206 44259 jjdelcerro
1207 46063 omartinez
                }
1208
                FeatureType ftype = this.store.getDefaultFeatureTypeQuietly();
1209
                SimpleFeaturesTableModelImpl emptyTableModel = new SimpleFeaturesTableModelImpl(
1210
                        ftype,
1211
                        resultColumnNames,
1212
                        null
1213
                );
1214
                this.tblResults.setModel(emptyTableModel);
1215
1216
        }
1217
1218
        public void setResultColumnNames(List<String> names) {
1219
                this.parameters.getResultColumnNames().clear();
1220
                this.parameters.getResultColumnNames().addAll(names);
1221 45996 omartinez
//        if (this.conditionPanels == null) {
1222
//            return;
1223
//        }
1224
//        SimpleFeaturesTableModelImpl model;
1225
////        model = (SimpleFeaturesTableModel) this.tblResults.getModel();
1226
//        List<Feature> features = store.getFeatures(this.parameters.getQuery());
1227
//        FacadeOfAFeaturePagingHelper facade = (FacadeOfAFeaturePagingHelper) features;
1228
//        FeatureType ftype = facade.getFeaturePagingHelper().getFeatureSet().getDefaultFeatureType();
1229
//        model = new SimpleFeaturesTableModelImpl(
1230
//                ftype,
1231
//                this.parameters.getResultColumnNames(),
1232
//                features
1233
//        );
1234
//        tblResults.setModel(model);
1235 46063 omartinez
        }
1236 44829 omartinez
1237 46063 omartinez
        @Override
1238
        public boolean setFilter(Expression filter) {
1239
                try {
1240 46505 fdiaz
                        if (!this.initialized) { //this.conditionPanels == null) {
1241
                                this.initComponents1();
1242 46063 omartinez
                        }
1243
                        if (ExpressionUtils.isPhraseEmpty(filter)) {
1244
                                this.clear();
1245
                                return true;
1246
                        }
1247
                        int panel = 0;
1248
                        int selected = PANEL_ADVANCED;
1249
                        for (SearchConditionPanel conditionPanel : conditionPanels) {
1250
                                if (panel != PANEL_ADVANCED && conditionPanel.set(filter)) {
1251
                                        selected = panel;
1252
                                }
1253
                                panel++;
1254
                        }
1255
                        this.tabSearchMode.setSelectedIndex(selected);
1256 44829 omartinez
1257 44794 omartinez
//            SimpleFeaturesTableModel model = new SimpleFeaturesTableModel(this.getStore());
1258
//            tblResults.setModel(model);
1259
//            lblMsg.setText("");
1260 46063 omartinez
                        return true;
1261
                } catch (Exception ex) {
1262
                        LOGGER.warn("Can't set current search", ex);
1263
                        return false;
1264
                }
1265
        }
1266 44707 jjdelcerro
1267 46063 omartinez
        @Override
1268
        public List<SearchConditionPanel> getConditionPanels() {
1269
                return Collections.unmodifiableList(this.conditionPanels);
1270
        }
1271 44712 jjdelcerro
1272 46063 omartinez
        @Override
1273
        public SearchConditionPanel getConditionPanel(String name) {
1274
                if (conditionPanels == null) {
1275
                        return null;
1276
                }
1277
                for (SearchConditionPanel panel : conditionPanels) {
1278
                        if (StringUtils.equalsIgnoreCase(name, panel.getFactory().getName())) {
1279
                                return panel;
1280
                        }
1281
                }
1282
                return null;
1283
        }
1284 44829 omartinez
1285 46900 jjdelcerro
        public FeatureSelection getSelectedFeatures() {
1286
                if (!this.initialized) {
1287
                        return null;
1288
                }
1289
                int[] selectedRows = this.tblResults.getSelectedRows();
1290
                if( ArrayUtils.isEmpty(selectedRows) ) {
1291
                    return null;
1292
                }
1293 47417 jjdelcerro
                if (this.tabResults.getSelectedIndex() == 1) {
1294
                    if (this.currentPostProcess == null) {
1295
                            return null;
1296
                    }
1297 46900 jjdelcerro
                    try {
1298
                            FeatureSelection selection = this.store.createFeatureSelection();
1299 47417 jjdelcerro
                            List<Feature> features = ((SimpleFeaturesTableModelImpl) this.tblSearchPostProcessResults.getModel()).getFeatures();
1300 46900 jjdelcerro
                            for (int i = 0; i < selectedRows.length ; i++) {
1301
                                Feature feature = features.get(selectedRows[i]);
1302
                                selection.select(feature);
1303
                            }
1304
                            return selection==null? null:selection;
1305
                    } catch (Exception ex) {
1306
                            LOGGER.warn("Can't build search for the selected feature.", ex);
1307
                            return null;
1308
                    }
1309
                } else {
1310
                    try {
1311
                            FeatureSelection selection = this.store.createFeatureSelection();
1312 47417 jjdelcerro
                            List<Feature> features = ((SimpleFeaturesTableModelImpl) this.tblResults.getModel()).getFeatures();
1313 46900 jjdelcerro
                            for (int i = 0; i < selectedRows.length ; i++) {
1314
                                Feature feature = features.get(selectedRows[i]);
1315
                                selection.select(feature);
1316
                            }
1317
                            return selection==null? null:selection;
1318
                    } catch (Exception ex) {
1319
                            LOGGER.warn("Can't build search for the selected feature.", ex);
1320
                            return null;
1321
                    }
1322
                }
1323
        }
1324
1325 47184 jjdelcerro
        @Override
1326 46900 jjdelcerro
        public Expression getFilterForSelectedFeatures() {
1327
                int maxfeatures = 100;
1328
1329
                if (!this.initialized) {
1330
                        return null;
1331
                }
1332
                int[] selectedRows = this.tblResults.getSelectedRows();
1333
                if( ArrayUtils.isEmpty(selectedRows) ) {
1334
                    return null;
1335
                }
1336
                if( selectedRows.length > maxfeatures ) {
1337
                    this.taskStatusController.message("Too many items selecteds");
1338
                }
1339 47418 fdiaz
                if (this.tabResults.getSelectedIndex() == 0) {
1340
                    try {
1341
                            FeatureType ftype = this.store.getDefaultFeatureType();
1342
                            ExpressionBuilder builder = ExpressionUtils.createExpressionBuilder();
1343
                            List<Feature> features = ((SimpleFeaturesTableModelImpl) this.tblResults.getModel()).getFeatures();
1344
                            for (int i = 0; i < selectedRows.length && i<maxfeatures ; i++) {
1345
                                Feature feature = features.get(selectedRows[i]);
1346
                                for (FeatureAttributeDescriptor attrdesc : ftype.getPrimaryKey()) {
1347
                                        builder.or(
1348
                                                builder.eq(
1349
                                                        builder.column(attrdesc.getName()),
1350
                                                        builder.constant(feature.get(attrdesc.getName()))
1351
                                                )
1352
                                        );
1353
                                }
1354
                            }
1355
                            Expression filter = ExpressionUtils.createExpression(builder.toString());
1356
                            return filter;
1357
                    } catch (Exception ex) {
1358
                            LOGGER.warn("Can't build search for the selected feature.", ex);
1359
                            return null;
1360
                    }
1361
                } else {
1362 46900 jjdelcerro
                        if (this.currentPostProcess == null) {
1363
                                return null;
1364
                        }
1365
                        try {
1366
                                ExpressionBuilder builder = ExpressionUtils.createExpressionBuilder();
1367
                                List<Feature> features = ((SimpleFeaturesTableModelImpl) this.tblSearchPostProcessResults.getModel()).getFeatures();
1368
                                for (int i = 0; i < selectedRows.length && i<maxfeatures; i++) {
1369
                                    Feature feature = features.get(selectedRows[i]);
1370
                                    FeatureType ftype = this.postProcessStore.getDefaultFeatureType();
1371
                                    for (FeatureAttributeDescriptor attrdesc : ftype.getPrimaryKey()) {
1372 47418 fdiaz
                                            builder.or(
1373 46900 jjdelcerro
                                                    builder.eq(
1374
                                                            builder.column(attrdesc.getName()),
1375
                                                            builder.constant(feature.get(attrdesc.getName()))
1376
                                                    )
1377
                                            );
1378
                                    }
1379
                                }
1380
                                Expression filter = ExpressionUtils.createExpression(builder.toString());
1381
                                return filter;
1382
                        } catch (Exception ex) {
1383
                                LOGGER.warn("Can't build search for the selected feature.", ex);
1384
                                return null;
1385
                        }
1386
                }
1387
        }
1388
1389 46063 omartinez
        @Override
1390
        public Expression getFilterForSelectedFeature() {
1391 46505 fdiaz
                if (!this.initialized) { //this.conditionPanels == null) {
1392 46063 omartinez
                        return null;
1393
                }
1394 47417 jjdelcerro
                if (this.tabResults.getSelectedIndex() == 1) {
1395
                        if (this.currentPostProcess == null) {
1396
                                return null;
1397
                        }
1398
                        int selectedRow = this.tblSearchPostProcessResults.getSelectedRow();
1399 46063 omartinez
                        if (selectedRow < 0) {
1400
                                return null;
1401
                        }
1402
                        try {
1403 47417 jjdelcerro
                                List<Feature> features = ((SimpleFeaturesTableModelImpl) this.tblSearchPostProcessResults.getModel()).getFeatures();
1404 46063 omartinez
                                Feature feature = features.get(selectedRow);
1405 45537 jolivas
1406 46063 omartinez
                                ExpressionBuilder builder = ExpressionUtils.createExpressionBuilder();
1407 47417 jjdelcerro
                                FeatureType ftype = this.postProcessStore.getDefaultFeatureType();
1408 46063 omartinez
                                for (FeatureAttributeDescriptor attrdesc : ftype.getPrimaryKey()) {
1409
                                        builder.and(
1410
                                                builder.eq(
1411
                                                        builder.column(attrdesc.getName()),
1412
                                                        builder.constant(feature.get(attrdesc.getName()))
1413
                                                )
1414
                                        );
1415
                                }
1416
                                Expression filter = ExpressionUtils.createExpression(builder.toString());
1417
                                return filter;
1418
                        } catch (Exception ex) {
1419
                                LOGGER.warn("Can't build search for the selected feature.", ex);
1420
                                return null;
1421
                        }
1422
                } else {
1423 47417 jjdelcerro
                        int selectedRow = this.tblResults.getSelectedRow();
1424 46063 omartinez
                        if (selectedRow < 0) {
1425
                                return null;
1426
                        }
1427
                        try {
1428 47417 jjdelcerro
                                List<Feature> features = ((SimpleFeaturesTableModelImpl) this.tblResults.getModel()).getFeatures();
1429 46063 omartinez
                                Feature feature = features.get(selectedRow);
1430 44829 omartinez
1431 46063 omartinez
                                ExpressionBuilder builder = ExpressionUtils.createExpressionBuilder();
1432 47417 jjdelcerro
                                FeatureType ftype = this.store.getDefaultFeatureType();
1433 46063 omartinez
                                for (FeatureAttributeDescriptor attrdesc : ftype.getPrimaryKey()) {
1434
                                        builder.and(
1435
                                                builder.eq(
1436
                                                        builder.column(attrdesc.getName()),
1437
                                                        builder.constant(feature.get(attrdesc.getName()))
1438
                                                )
1439
                                        );
1440
                                }
1441
                                Expression filter = ExpressionUtils.createExpression(builder.toString());
1442
                                return filter;
1443
                        } catch (Exception ex) {
1444
                                LOGGER.warn("Can't build search for the selected feature.", ex);
1445
                                return null;
1446
                        }
1447
                }
1448 45537 jolivas
1449 46063 omartinez
        }
1450 45537 jolivas
1451 46063 omartinez
        @Override
1452
        public FeatureStore getStore() {
1453
                return store;
1454
        }
1455 44644 jjdelcerro
1456 46063 omartinez
        private void doOrderBy() {
1457 46585 fdiaz
            try {
1458
                LOGGER.info("Do show order by");
1459 46063 omartinez
                I18nManager i18n = ToolsLocator.getI18nManager();
1460
                WindowManager_v2 windowManager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
1461
                FeatureQueryOrderPanel orderPanel = DALSwingLocator.getDataSwingManager().createFeatureStoreOrderPanel();
1462
                orderPanel.setStore(store);
1463
                orderPanel.put(parameters.getQuery());
1464
                Dialog dialog = windowManager.createDialog(
1465
                        orderPanel.asJComponent(),
1466
                        i18n.getTranslation("_Select_order"),
1467
                        null,
1468
                        WindowManager_v2.BUTTONS_OK_CANCEL
1469
                );
1470
                dialog.addActionListener((ActionEvent e) -> {
1471
                        if (dialog.getAction() == WindowManager_v2.BUTTON_OK) {
1472
                                orderPanel.fetch(this.parameters.getQuery());
1473
                                search();
1474
                        }
1475
                });
1476
                dialog.show(WindowManager.MODE.DIALOG);
1477 46585 fdiaz
            } catch (Exception ex) {
1478
                LOGGER.warn("Can't show dialog", ex);
1479
            }
1480 46571 fdiaz
        }
1481 46063 omartinez
1482 46571 fdiaz
    private void doExportTSV(JTable table) {
1483 46585 fdiaz
        try {
1484
            LOGGER.info("Do export TSV");
1485
            final SimpleFeaturesTableModel model;
1486
            if (table.getModel() instanceof SimpleFeaturesTableModel) {
1487
                model = (SimpleFeaturesTableModel) table.getModel();
1488
            } else {
1489
                model = null;
1490
            }
1491
            I18nManager i18n = ToolsLocator.getI18nManager();
1492
            if (model == null) {
1493
                ToolsSwingLocator.getThreadSafeDialogsManager().messageDialog(
1494
                        i18n.getTranslation("_Not_able_to_export_table_to_TSV"),
1495 47228 fdiaz
                        i18n.getTranslation(EXPORT_TO_TSV_TITLE),
1496 46585 fdiaz
                        JOptionPane.WARNING_MESSAGE);
1497
                return;
1498
            }
1499 46571 fdiaz
1500
            FileFilter fileFilter = new FileFilter() {
1501
                @Override
1502
                public boolean accept(File f) {
1503
                    if (f.isDirectory()) {
1504
                        return true;
1505
                    }
1506
                    String extension = FilenameUtils.getExtension(f.getAbsolutePath());
1507
                    return StringUtils.equalsIgnoreCase(TSV_EXTENSION, extension);
1508
                }
1509 46585 fdiaz
1510 46571 fdiaz
                @Override
1511
                public String getDescription() {
1512
                    return "TSV file";
1513
                }
1514
            };
1515 46585 fdiaz
            FoldersManager folderManager = ToolsLocator.getFoldersManager();
1516 47228 fdiaz
            File initialFolder = folderManager.getLastPath(EXPORT_TO_TSV_LASTPATHID);
1517 46571 fdiaz
1518 46585 fdiaz
            ThreadSafeDialogsManager safeDialogsManager = ToolsSwingLocator.getThreadSafeDialogsManager();
1519
            ImmutablePair<File[], Charset> pair = safeDialogsManager.showChooserDialog(
1520 47228 fdiaz
                    i18n.getTranslation(EXPORT_TO_TSV_TITLE),
1521 46571 fdiaz
                    SAVE_DIALOG,
1522
                    FILES_ONLY,
1523
                    false,
1524
                    initialFolder,
1525
                    fileFilter,
1526
                    initialized,
1527
                    true
1528
            );
1529
1530 46585 fdiaz
            if (pair == null) {
1531 46571 fdiaz
                return;
1532
            }
1533 46585 fdiaz
            File[] files = pair.getLeft();
1534
            Charset charset = pair.getRight();
1535
            if (files.length < 1) {
1536
                return;
1537 46571 fdiaz
            }
1538 46585 fdiaz
            File f = files[0];
1539
            if (f == null) {
1540
                return;
1541
            }
1542
            if (f.isDirectory()) {
1543
                return;
1544
            }
1545
            if (FilenameUtils.getExtension(f.getName()).isEmpty()) {
1546
                f = new File(f.getAbsolutePath() + FilenameUtils.EXTENSION_SEPARATOR + "tsv");
1547
            }
1548
            if (f.exists()) {
1549
                int res = safeDialogsManager.confirmDialog(
1550
                        i18n.getTranslation("fichero_ya_existe_seguro_desea_guardarlo"),
1551 47228 fdiaz
                        i18n.getTranslation(EXPORT_TO_TSV_TITLE),
1552 46585 fdiaz
                        WIDTH,
1553
                        HEIGHT
1554
                );
1555
                if (res != YES_OPTION) {
1556
                    return;
1557
                }
1558
            }
1559 46571 fdiaz
1560 46585 fdiaz
            final File file = f;
1561
1562 47228 fdiaz
            folderManager.setLastPath(EXPORT_TO_TSV_LASTPATHID, file.getParentFile());
1563 46585 fdiaz
            Cursor savedCursor = this.getCursor();
1564
            SimpleTaskStatus status = ToolsLocator.getTaskStatusManager().createDefaultSimpleTaskStatus("");
1565
            status.setAutoremove(true);
1566
            status.add();
1567
            this.taskStatusController.bind(status);
1568 47221 jjdelcerro
1569
            SearchParameters searchParams = this.fetch(this.parameters.getCopy());
1570
            final FeatureQuery myQuery;
1571
            if( this.useSelection() ) {
1572
                myQuery = this.addSelection(this.store, searchParams.getQueryToApply());
1573
            } else {
1574
                myQuery = searchParams.getQueryToApply();
1575
            }
1576
1577 46585 fdiaz
            Thread task = new Thread(() -> {
1578
                try {
1579
                    this.processing = true;
1580
                    this.updateComponentState();
1581
                    SwingUtilities.invokeLater(() -> {
1582
                        this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
1583
                    });
1584 47228 fdiaz
                    status.setTitle(i18n.getTranslation(EXPORT_TO_TSV_TITLE));
1585 46585 fdiaz
1586 47228 fdiaz
                    Pair<Iterator<Feature>, Long> features = buildExportIterator(table, store, myQuery);
1587
1588 46585 fdiaz
                    ExportTSV exportTSV = new ExportTSV();
1589 47228 fdiaz
                    exportTSV.process(features.getLeft(), features.getRight(), model, file, charset, status);
1590
1591 46585 fdiaz
                } catch (Exception ex) {
1592
                    LOGGER.warn("Not able to export table to TSV", ex);
1593
                } finally {
1594
                    this.processing = false;
1595
                    SwingUtilities.invokeLater(() -> {
1596
                        this.setCursor(savedCursor);
1597
                    });
1598
                    this.updateComponentState();
1599
                }
1600
            }, "SearchPanelExportTSV");
1601
            task.start();
1602
        } catch (Exception ex) {
1603
            LOGGER.warn("Can't export TSV", ex);
1604
        }
1605 46571 fdiaz
    }
1606
1607 46063 omartinez
        private void doCopyRows(JTable table) {
1608 46585 fdiaz
                LOGGER.info("Do copy rows");
1609 47228 fdiaz
                if (!(table.getModel() instanceof SimpleFeaturesTableModel)) {
1610
                    LOGGER.warn("Can't copy rows, wrong model.");
1611
                    return;
1612
                }
1613
1614
                final SimpleFeaturesTableModel model = (SimpleFeaturesTableModel) table.getModel();
1615
1616
                Cursor savedCursor = this.getCursor();
1617 46063 omartinez
                SimpleTaskStatus status = ToolsLocator.getTaskStatusManager().createDefaultSimpleTaskStatus("");
1618
                status.setAutoremove(true);
1619
                status.add();
1620
                this.taskStatusController.bind(status);
1621
                Thread task = new Thread(() -> {
1622
                        try {
1623
                                this.processing = true;
1624 46066 omartinez
                                this.updateComponentState();
1625 46063 omartinez
                                SwingUtilities.invokeLater(() -> {
1626
                                        this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
1627
                                });
1628 47228 fdiaz
                                String title = ToolsLocator.getI18nManager().getTranslation("_Copying_rows_to_clipboard");
1629
                                status.setTitle(title);
1630
                                status.message("");
1631
                                SearchParameters searchParams = this.fetch(this.parameters.getCopy());
1632
                                final FeatureQuery myQuery;
1633
                                if( this.useSelection() ) {
1634
                                    myQuery = this.addSelection(this.store, searchParams.getQueryToApply());
1635
                                } else {
1636
                                    myQuery = searchParams.getQueryToApply();
1637
                                }
1638
1639
                                Pair<Iterator<Feature>, Long> features = buildExportIterator(table, store, myQuery);
1640
1641
                                ExportTSV exportTSV = new ExportTSV();
1642
                                ByteArrayOutputStream fos = new ByteArrayOutputStream();
1643
1644
                                exportTSV.process(
1645
                                        features.getLeft(),
1646
                                        features.getRight(),
1647
                                        model,
1648
                                        fos,
1649
                                        Charset.defaultCharset(),
1650
                                        status
1651
                                );
1652 44829 omartinez
1653 47228 fdiaz
                                String toStr = new String(fos.toByteArray(),Charset.defaultCharset());
1654 45695 omartinez
1655 46066 omartinez
                                SwingUtilities.invokeLater(() -> {
1656 47228 fdiaz
                                        ToolsSwingLocator.getToolsSwingManager().putInClipboard(toStr);
1657 46066 omartinez
                                        status.setTitle(ToolsLocator.getI18nManager().getTranslation("_Copy_ended"));
1658
                                        status.terminate();
1659
                                });
1660 46051 omartinez
1661 46063 omartinez
                        } catch (Exception ex) {
1662
                                LOGGER.warn("Not able to copy rows to the clipboard", ex);
1663
                                status.message("Not able to copy rows to the clipboard");
1664
                                status.abort();
1665
                        } finally {
1666
                                this.processing = false;
1667
                                SwingUtilities.invokeLater(() -> {
1668
                                        this.setCursor(savedCursor);
1669
                                });
1670
                                this.updateComponentState();
1671
                        }
1672
                }, "SearchPanelCopyRows");
1673
                task.start();
1674
        }
1675 45695 omartinez
1676 47228 fdiaz
    private Pair<Iterator<Feature>, Long> buildExportIterator(JTable table, FeatureStore store, FeatureQuery query) {
1677
1678
        if (!(table.getModel() instanceof SimpleFeaturesTableModel)) {
1679
            return null;
1680
        }
1681 45695 omartinez
1682 47228 fdiaz
        final SimpleFeaturesTableModel model = (SimpleFeaturesTableModel) table.getModel();
1683
1684
        int[] selection = table.getSelectedRows();
1685
1686
        if(ArrayUtils.isEmpty(selection) || selection.length == model.size()) {
1687
            FeatureSet features = null;
1688
            try {
1689
                features = store.getFeatureSet(query);
1690
                return new ImmutablePair<>(features.fastIterator(),features.size64());
1691
            } catch(Exception e) {
1692
                throw new RuntimeException("Can't get features.", e);
1693
            } finally {
1694
                DisposeUtils.disposeQuietly(features);
1695
            }
1696
        }
1697
        Iterator<Feature> featIterator = new Iterator<Feature>() {
1698
            int row = 0;
1699 44259 jjdelcerro
1700 47228 fdiaz
            @Override
1701
            public boolean hasNext() {
1702
                return row < selection.length;
1703
            }
1704
1705
            @Override
1706
            public Feature next() {
1707
                int n = table.convertRowIndexToModel(selection[row++]);
1708
                return model.getFeatureAt(n);
1709
            }
1710
        };
1711
        return new ImmutablePair<>(featIterator, (long)selection.length);
1712
1713
    }
1714
1715 46063 omartinez
        @Override
1716
        public ImageIcon loadImage(String imageName) {
1717 46863 jjdelcerro
            return ToolsSwingUtils.loadImage(this, imageName);
1718 46063 omartinez
        }
1719 44829 omartinez
1720 46063 omartinez
        @Override
1721
        public int getSelectedFeatureCount() {
1722 46505 fdiaz
                if (!this.initialized) { //this.conditionPanels == null) {
1723 46063 omartinez
                        return 0;
1724
                }
1725 47417 jjdelcerro
                if (this.currentPostProcess != null && this.tabResults.getSelectedIndex() == 1) {
1726
                        return this.tblSearchPostProcessResults.getSelectedRowCount();
1727 46063 omartinez
                }
1728 47417 jjdelcerro
                return this.tblResults.getSelectedRowCount();
1729 46063 omartinez
        }
1730 44275 jjdelcerro
1731 46063 omartinez
        @Override
1732
        public JComponent getActionButton(String name) {
1733
                ActionButtons actionButton = this.actions.get(name);
1734
                if (actionButton == null) {
1735
                        return null;
1736
                }
1737
                return actionButton.button;
1738
        }
1739 44829 omartinez
1740 46063 omartinez
        @Override
1741
        public void setShowActions(boolean showActions) {
1742
                this.showActions = showActions;
1743
        }
1744 44351 jjdelcerro
1745 46063 omartinez
        @Override
1746
        public boolean isShowActions() {
1747
                return this.showActions;
1748
        }
1749 44712 jjdelcerro
1750 46063 omartinez
        private void doCalculatedColumns() {
1751 46585 fdiaz
            try {
1752
                LOGGER.info("Do show calculate columns");
1753 46063 omartinez
                WindowManager_v2 winmanager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
1754
                I18nManager i18n = ToolsLocator.getI18nManager();
1755
                final FeatureQueryCalculatedColumnsPanel panel = new DefaultFeatureQueryCalculatedColumnsPanel();
1756
                panel.setStore(this.store);
1757
                panel.put(this.parameters.getQuery());
1758
                final Dialog dialog = winmanager.createDialog(
1759
                        panel.asJComponent(),
1760
                        i18n.getTranslation("_Calculated_columns"),
1761
                        null,
1762
                        WindowManager_v2.BUTTONS_OK_CANCEL
1763
                );
1764
                dialog.addActionListener((ActionEvent e) -> {
1765
                        if (dialog.getAction() == WindowManager_v2.BUTTONS_OK) {
1766
                                panel.fetch(this.parameters.getQuery());
1767
                                search();
1768
                        }
1769
                });
1770
                dialog.show(WindowManager.MODE.DIALOG);
1771 46585 fdiaz
            } catch (Exception ex) {
1772
                LOGGER.warn("Can't show dialog", ex);
1773
            }
1774 46063 omartinez
        }
1775 44707 jjdelcerro
1776 46063 omartinez
        private void doGroupBy() {
1777 46585 fdiaz
            try {
1778
                LOGGER.info("Do show group by");
1779 46063 omartinez
                DataStoreProviderFactory dataFactory = this.store.getProviderFactory();
1780
                int allowGroupBy = ((FeatureStoreProviderFactory) dataFactory).allowGroupBy();
1781
                if (allowGroupBy != DataType.YES) {
1782
                        // FIXME: mensaje al usaurio.
1783
                        I18nManager i18n = ToolsLocator.getI18nManager();
1784
                        ThreadSafeDialogsManager dialogs = ToolsSwingLocator.getThreadSafeDialogsManager();
1785
                        dialogs.messageDialog(
1786
                                i18n.getTranslation("_The_group_function_is_not_available_for_this_table"),
1787
                                i18n.getTranslation("_Information"),
1788
                                JOptionPane.INFORMATION_MESSAGE
1789
                        );
1790
                        return;
1791
                }
1792 44712 jjdelcerro
1793 46063 omartinez
                WindowManager_v2 winmanager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
1794
                I18nManager i18n = ToolsLocator.getI18nManager();
1795 46536 fdiaz
                final DefaultSearchGroupByPanel panelGroupBy = new DefaultSearchGroupByPanel();
1796 46063 omartinez
                panelGroupBy.setStore(this.store);
1797 46536 fdiaz
                panelGroupBy.put(this.parameters);
1798 46063 omartinez
                final Dialog dialog = winmanager.createDialog(
1799
                        panelGroupBy.asJComponent(),
1800
                        i18n.getTranslation("_Select_group_columns_and_aggregate_functions"),
1801
                        null,
1802
                        WindowManager_v2.BUTTONS_OK_CANCEL
1803
                );
1804
                dialog.addActionListener((ActionEvent e) -> {
1805
                        if (dialog.getAction() == WindowManager_v2.BUTTONS_OK) {
1806 46536 fdiaz
                                panelGroupBy.fetch(this.parameters);
1807 46063 omartinez
                                search();
1808
                        }
1809
                });
1810
                dialog.show(WindowManager.MODE.DIALOG);
1811 46585 fdiaz
            } catch (Exception ex) {
1812
                LOGGER.warn("Can't show dialog", ex);
1813
            }
1814 46063 omartinez
        }
1815 44829 omartinez
1816 46063 omartinez
        private void doSelectResultColumnNames() {
1817 46585 fdiaz
            try {
1818
                LOGGER.info("Do select result column names");
1819 46063 omartinez
                WindowManager_v2 winmanager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
1820
                I18nManager i18n = ToolsLocator.getI18nManager();
1821
                final FeatureAttributesSelectionPanel panelSelectColumns = DALSwingLocator.getManager().createFeatureAttributeSelectionPanel();
1822
                panelSelectColumns.allowCalculatedAttributes(false);
1823
                FeatureType ftype = this.getFeatureType();
1824
                panelSelectColumns.setFeatureType(ftype);
1825 46536 fdiaz
                if(this.parameters.getQuery() != null){
1826
                    panelSelectColumns.setExtraColumns(this.parameters.getQuery().getExtraColumns().getColumns());
1827
                }
1828 46063 omartinez
                panelSelectColumns.setSelectedNames(this.parameters.getResultColumnNames());
1829
                final Dialog dialog = winmanager.createDialog(
1830
                        panelSelectColumns.asJComponent(),
1831
                        i18n.getTranslation("_Select_the_columns_to_display"),
1832
                        null,
1833
                        WindowManager_v2.BUTTONS_OK_CANCEL
1834
                );
1835
                dialog.addActionListener((ActionEvent e) -> {
1836
                        if (dialog.getAction() == WindowManager_v2.BUTTONS_OK) {
1837
                                this.setResultColumnNames(panelSelectColumns.getSelectedNames());
1838
                                search();
1839
                        }
1840
                });
1841
                dialog.show(WindowManager.MODE.DIALOG);
1842 46585 fdiaz
            } catch (Exception ex) {
1843
                LOGGER.warn("Can't show dialog", ex);
1844
            }
1845 46063 omartinez
        }
1846
1847
        @Override
1848
        public void put(SearchParameters inParams) {
1849
                this.parameters = (DefaultSearchParameters) inParams;
1850
                for (SearchConditionPanel conditionPanel : this.conditionPanels) {
1851
                        try {
1852
                                conditionPanel.put(inParams);
1853
                        } catch (Exception ex) {
1854
                                LOGGER.warn("Can't open panel", ex);
1855
                        }
1856
                }
1857
                this.tabSearchMode.setSelectedIndex(inParams.getSearchMode());
1858 44829 omartinez
1859 46063 omartinez
        }
1860 44707 jjdelcerro
1861 46063 omartinez
        private FeatureQuery getQuery() {
1862
                FeatureQuery query;
1863
                try {
1864
                        int searchMode = this.tabSearchMode.getSelectedIndex();
1865
                        SearchConditionPanel panel = this.conditionPanels.get(searchMode);
1866
                        Expression filter = panel.get();
1867
                        if (searchMode != PANEL_ADVANCED) {
1868
                                this.conditionPanels.get(PANEL_ADVANCED).set(filter);
1869
                        }
1870
                        query = (FeatureQuery) this.parameters.getQuery().clone();
1871
                        query.retrievesAllAttributes();
1872
                        if (ExpressionUtils.isPhraseEmpty(filter)) {
1873
                                return query;
1874
                        }
1875 47303 jjdelcerro
                        query.setFilter(Expression.cloneQuietly(filter));
1876 46063 omartinez
                        query.retrievesAllAttributes();
1877
                        return query;
1878
                } catch (Exception ex) {
1879
                        LOGGER.warn("Can't build query.", ex);
1880
                        return null;
1881
                }
1882
        }
1883 44712 jjdelcerro
1884 46063 omartinez
        @Override
1885
        public SearchParameters fetch(SearchParameters outParams) {
1886 46536 fdiaz
            if(!initialized){
1887
                this.initComponents1();
1888
            }
1889 46063 omartinez
                // Actualiza el fquery del parameters con los paneles
1890
                for (SearchConditionPanel conditionPanel : conditionPanels) {
1891
                        try {
1892
                                conditionPanel.fetch(this.parameters);
1893
                        } catch (Exception ex) {
1894
                                LOGGER.warn("Panel not able to fetch values", ex);
1895
                        }
1896
                }
1897 44829 omartinez
1898 46063 omartinez
                // Actualiza el filtro con el panel activo
1899
                int searchMode = this.tabSearchMode.getSelectedIndex();
1900
                SearchConditionPanel panel = this.conditionPanels.get(searchMode);
1901
                Expression filter = panel.get();
1902
                if (searchMode != PANEL_ADVANCED) {
1903
                        this.conditionPanels.get(PANEL_ADVANCED).set(filter);
1904
                }
1905
                this.parameters.setSearchMode(searchMode);
1906
                FeatureQuery query = (FeatureQuery) this.parameters.getQuery();
1907
                this.lastQuery = query.getCopy();
1908
                query.retrievesAllAttributes();
1909
                query.clearFilter();
1910
                if (!ExpressionUtils.isPhraseEmpty(filter)) {
1911
                        query.setFilter(filter);
1912
                        query.retrievesAllAttributes();
1913
                }
1914 44829 omartinez
1915 46063 omartinez
                if (outParams == null) {
1916
                        return this.parameters.getCopy();
1917
                }
1918
                outParams.copyFrom(this.parameters.getCopy());
1919
                return outParams;
1920
        }
1921 44829 omartinez
1922 46063 omartinez
        public static void selfRegister() {
1923 46863 jjdelcerro
            boolean n = ToolsSwingUtils.registerIcons(
1924
                    DefaultSearchPanel.class,
1925
                    "",
1926
                    LIBRARY_NAME,
1927
                    new String[]{"search", "featurestore-column"},
1928
                    new String[]{"search", "featurestore-foreing-key"},
1929
                    new String[]{"search", "featurestore-table"},
1930
                    new String[]{"search", "search-action-select"},
1931
                    new String[]{"search", "search-action-select-add"},
1932
                    new String[]{"search", "search-action-select-filter"},
1933
                    new String[]{"search", "search-nullbehavior-null"},
1934
                    new String[]{"search", "search-nullbehavior-true"},
1935 47264 jjdelcerro
                    new String[]{"search", "search-nullbehavior-false"},
1936
                    new String[]{"search", "search-geometry-select"}
1937 46863 jjdelcerro
            );
1938 44712 jjdelcerro
1939 46863 jjdelcerro
            ConfigurableActionsMamager cfgActionsManager = ToolsUtilLocator.getConfigurableActionsMamager();
1940
            cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new UseLabelsYesAction());
1941
            cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new UseLabelsNoAction());
1942
            cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new UseLabelsBothAction());
1943
            cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new SelectColumnsAction());
1944
            cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new CalculatedColumnsAction());
1945
            cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new GroupByAction());
1946
            cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new OrderByAction());
1947
            cfgActionsManager.addConfigurableAction(CONFIGURABLE_PANEL_ID, new PropertiesAction());
1948 46063 omartinez
        }
1949
1950
        private void doSelectSearchPostprocess() throws DataException {
1951
                DataSwingManager manager = DALSwingLocator.getDataSwingManager();
1952
                Map<String, SearchPostProcessFactory> searchPostProcessFactoryMap = manager.getSearchPostProcess();
1953
1954
                JPopupMenu menu = new JPopupMenu();
1955
                for (String factory : searchPostProcessFactoryMap.keySet()) {
1956
                        JMenuItem item;
1957
                        item = new JMenuItem(factory);
1958
                        SearchParameters searchParams = this.fetch(this.parameters.getCopy());
1959 46594 jjdelcerro
                        FeatureQuery myQuery = searchParams.getQueryToApply();
1960 46587 jjdelcerro
                        item.addActionListener((ActionEvent e) -> {
1961 46063 omartinez
                                doSearchPostProcess(store, myQuery, manager.getSearchPostProcess(factory), searchParams);
1962
                        });
1963
                        menu.add(item);
1964
                }
1965
                menu.show(this.btnSearchPostProcess, 0, this.btnSearchPostProcess.getHeight());
1966
        }
1967 45537 jolivas
1968 46063 omartinez
        private void doExecuteSearchPostProcess(
1969
                FeatureStore input,
1970
                FeatureQuery query,
1971
                SearchPostProcessFactory factory,
1972
                DynObject parameters
1973
        ) {
1974 46585 fdiaz
                LOGGER.info("Do execute post process");
1975 46062 omartinez
                Cursor savedCursor = this.getCursor();
1976
                SimpleTaskStatus status = ToolsLocator.getTaskStatusManager().createDefaultSimpleTaskStatus("");
1977 46063 omartinez
                status.setAutoremove(true);
1978
                status.add();
1979
                this.taskStatusController.bind(status);
1980
                Thread task = new Thread(() -> {
1981
                        try {
1982
                                SwingUtilities.invokeLater(() -> {
1983
                                        this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
1984
                                });
1985
                                this.processing = true;
1986
                                this.updateComponentState();
1987
                                SearchPostProcess process = factory.createProcess(factory, input, query, parameters);
1988 45537 jolivas
1989 46063 omartinez
                                if (parameters != null) {
1990
                                        process.setParameters(parameters);
1991
                                }
1992
                                //Ejecutar el execute en thread para no bloquear el software
1993
                                SearchPostProcess.SearchPostProcessResult output = process.execute(input, query, parameters, status);
1994 46062 omartinez
                                if (output != null) {
1995
                                        this.postProcessStore = output.getStore();
1996
                                        this.postProcessQuery = output.getQuery();
1997
1998
                                        doLoadSearchPostProccessResults(this.postProcessStore);
1999
2000
                                }
2001 46063 omartinez
                                this.currentPostProcess = factory.getName();
2002 46062 omartinez
                                status.terminate();
2003 46063 omartinez
2004
                        } catch (Exception ex) {
2005
                                LOGGER.warn("SearchPostProcess not able to be executed.", ex);
2006
                                resetPostProcessTable();
2007 46062 omartinez
                                status.setTitle(ToolsLocator.getI18nManager().getTranslation("_Error_in_post_process_operation"));
2008
                                status.message("");
2009
                                status.abort();
2010 46063 omartinez
                        } finally {
2011
                                SwingUtilities.invokeLater(() -> {
2012
                                        this.setCursor(savedCursor);
2013
                                });
2014
                                this.processing = false;
2015
                                this.updateComponentState();
2016
                        }
2017
                }, "ExecuteSearchPostProcess");
2018 45537 jolivas
2019 46063 omartinez
                task.start();
2020 45537 jolivas
2021 46063 omartinez
        }
2022 45537 jolivas
2023 46063 omartinez
        private void doLoadSearchPostProccessResults(FeatureStore input) {
2024 46062 omartinez
                if (!SwingUtilities.isEventDispatchThread()) {
2025 46063 omartinez
                        SwingUtilities.invokeLater(() -> {
2026 46062 omartinez
                                doLoadSearchPostProccessResults(input);
2027
                        });
2028 46063 omartinez
                        return;
2029
                }
2030 45537 jolivas
2031 46063 omartinez
                final List<Feature> featuresSearchPostProccessResults;
2032
                final FeatureQuery finalQuery;
2033
                finalQuery = null;
2034
                try {
2035
                        this.tabResults.setEnabledAt(1, true);
2036
                        this.tabResults.setSelectedIndex(1);
2037
                        featuresSearchPostProccessResults = input.getFeatures(finalQuery, 20);
2038
                        FacadeOfAFeaturePagingHelper facadeSearchPostProccessResults = (FacadeOfAFeaturePagingHelper) featuresSearchPostProccessResults;
2039
                        FeatureType ftypeSearchPostProccessResults = facadeSearchPostProccessResults.getFeaturePagingHelper().getFeatureSet().getDefaultFeatureType();
2040
                        // al modelo le pasamos el ftype de esas features
2041
                        resultPostProcessModel = new SimpleFeaturesTableModelImpl(
2042
                                ftypeSearchPostProccessResults,
2043
                                this.parameters.getResultColumnNames(),
2044
                                featuresSearchPostProccessResults
2045
                        );
2046 45537 jolivas
2047 46063 omartinez
                        I18nManager i18n = ToolsLocator.getI18nManager();
2048
                        TableModel oldmodel = tblSearchPostProcessResults.getModel();
2049
                        tblSearchPostProcessResults.setModel(resultPostProcessModel);
2050
                        resultPostProcessModel.setCellRenderers(tblSearchPostProcessResults);
2051
                        if (oldmodel instanceof SimpleFeaturesTableModel) {
2052
                                ((SimpleFeaturesTableModel) oldmodel).dispose();
2053
                        }
2054
                        updateNumberElementsMsg(resultPostProcessModel);
2055 45537 jolivas
//            if (resultPostProcessModel.hasErrors()) {
2056
//                lblMsg.setText("_Errors_occurred_load_search_post_process");
2057
//            } else {
2058
//                lblMsg.setText(String.format("%d " + i18n.getTranslation("_elements"), resultPostProcessModel.getRowCount()));
2059
//            }
2060 46063 omartinez
                } catch (Exception ex) {
2061
                        resetPostProcessTable();
2062
                        LOGGER.warn("SearchPostProcess not able to be executed. Can't get features or create table model", ex);
2063
                }
2064
        }
2065 45537 jolivas
2066 46063 omartinez
        private void updateComponentState() {
2067
                if (!SwingUtilities.isEventDispatchThread()) {
2068
                        SwingUtilities.invokeLater(this::updateComponentState);
2069
                        return;
2070
                }
2071
                this.pgbStatus.setVisible(processing);
2072
                this.setEnabled(!processing);
2073
        }
2074 45537 jolivas
2075 46063 omartinez
        private void resetPostProcessTable() {
2076
                if (!SwingUtilities.isEventDispatchThread()) {
2077
                        SwingUtilities.invokeLater(this::resetPostProcessTable);
2078
                        return;
2079
                }
2080 45537 jolivas
2081 46063 omartinez
                this.tblSearchPostProcessResults.setModel(new DefaultTableModel());
2082
        }
2083 45537 jolivas
2084 46063 omartinez
        private void doSearchPostProcess(FeatureStore store, FeatureQuery query, SearchPostProcessFactory factory, SearchParameters searchParams) {
2085 46585 fdiaz
                LOGGER.info("Do search post process");
2086 46063 omartinez
                if (factory.hasProcessParameters()) {
2087
                        DynObject parametersPostProcess = factory.createProcessParameters(store, query, searchParams);
2088
                        JDynForm form = DynFormLocator.getDynFormManager().createJDynForm(parametersPostProcess);
2089
                        form.setLayoutMode(JDynForm.USE_SEPARATORS);
2090 45537 jolivas
2091 46063 omartinez
                        I18nManager i18n = ToolsLocator.getI18nManager();
2092
                        WindowManager_v2 windowManager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
2093
2094
                        Dialog dialog = windowManager.createDialog(
2095
                                form.asJComponent(),
2096
                                i18n.getTranslation("_Postprocess_parameters"),
2097
                                i18n.getTranslation(
2098
                                        "_Parameters_for_XpostprocessNameX_postprocess_on_XtableNameX",
2099
                                        new String[]{
2100
                                                factory.getName(),
2101
                                                this.store.getName()
2102
                                        }
2103
                                ),
2104
                                WindowManager_v2.BUTTONS_OK_CANCEL);
2105
2106
                        ToolsSwingUtils.ensureRowsCols(dialog.asJComponent(), 20, 60, 30, 100);
2107
                        dialog.addActionListener((ActionEvent e2) -> {
2108
                                if (dialog.getAction() == WindowManager_v2.BUTTON_OK) {
2109
                                        form.getValues(parametersPostProcess); // actualiza el valor de lo los parametros con los valores introducidos por el usuario
2110
                                        doExecuteSearchPostProcess(store, query, factory, parametersPostProcess);
2111
                                        this.postProcessParams = parametersPostProcess;
2112
                                }
2113
                        });
2114
2115
                        dialog.show(WindowManager.MODE.DIALOG);
2116
2117
                } else {
2118
                        doExecuteSearchPostProcess(store, query, factory, null);
2119
                }
2120
        }
2121
2122
        private void updateNumberElementsMsg(SimpleFeaturesTableModel model) {
2123
                I18nManager i18n = ToolsLocator.getI18nManager();
2124
2125
                if (model.hasErrors()) {
2126
                        this.taskStatusController.setTitle(i18n.getTranslation("_Errors_occurred_load_search_post_process"));
2127
                } else {
2128
                        this.taskStatusController.setTitle(String.format("%d " + i18n.getTranslation("_elements"), model.getRowCount()));
2129
                }
2130
        }
2131
2132
        @Override
2133
        public boolean isVisible(Object component) {
2134 46665 jjdelcerro
                if (this.filterOnlyMode || !this.isGroupByEnabled()) {
2135 46063 omartinez
                        if (component instanceof GroupByAction) {
2136
                                return false;
2137
                        }
2138 45794 jjdelcerro
//            if( component instanceof OrderByAction ) {
2139
//                return false;
2140
//            }
2141 46010 jjdelcerro
//            if( component instanceof CalculatedColumnsAction ) {
2142
//                return false;
2143
//            }
2144 46063 omartinez
                }
2145
                return true;
2146
        }
2147 45537 jolivas
2148 46063 omartinez
        @Override
2149
        public boolean isEnabled(Object component) {
2150
                if (component instanceof GroupByAction) {
2151
                        DataStoreProviderFactory dataFactory = this.store.getProviderFactory();
2152
                        int allowGroupBy = ((FeatureStoreProviderFactory) dataFactory).allowGroupBy();
2153
                        if (allowGroupBy != DataType.YES) {
2154
                                return false;
2155
                        }
2156
                }
2157
                return true;
2158
        }
2159 45379 jjdelcerro
2160 46063 omartinez
        @Override
2161
        public void setFilterOnlyMode(boolean filterOnlyMode) {
2162 46617 fdiaz
            if (this.initialized) {
2163
                throw new IllegalStateException("Cannot change filter-only-mode after invoking asJComponent.");
2164
            }
2165
            this.filterOnlyMode = filterOnlyMode;
2166 46665 jjdelcerro
            this.groupByEnabled = false;
2167
            this.postProcessEnabled = false;
2168 46617 fdiaz
            this.showActions = false;
2169
        }
2170 45379 jjdelcerro
2171 46063 omartinez
        @Override
2172
        public boolean isFilterOnlyMode() {
2173
                return this.filterOnlyMode;
2174
        }
2175 45379 jjdelcerro
2176 46063 omartinez
        @Override
2177
        public Feature getLastSelectedFeature() {
2178
                return this.lastSelectedFeature;
2179
        }
2180 45794 jjdelcerro
2181 46063 omartinez
        @Override
2182
        public Object getProperty(String name) {
2183
                return this.propertiesHelper.getProperty(name);
2184
        }
2185 46010 jjdelcerro
2186 46063 omartinez
        @Override
2187
        public void setProperty(String name, Object value) {
2188
                this.propertiesHelper.setProperty(name, value);
2189
        }
2190 46010 jjdelcerro
2191 46063 omartinez
        @Override
2192
        public Map<String, Object> getProperties() {
2193
                return this.propertiesHelper.getProperties();
2194
        }
2195 46010 jjdelcerro
2196 47184 jjdelcerro
        @Override
2197 46485 fdiaz
    public void setAutomaticallySearch(boolean automaticallySearch){
2198
        this.automaticallySearch = automaticallySearch;
2199
    }
2200
2201 47184 jjdelcerro
        @Override
2202 46485 fdiaz
    public boolean isAutomaticallySearch(){
2203
        return automaticallySearch;
2204
    }
2205 46517 fdiaz
2206
    @Override
2207
    public String getLastErrorMessage() {
2208
        return this.lastErrorMessage;
2209
    }
2210
2211
    private String getLastErrorMessage(Throwable ex) {
2212
        StringBuilder builder = new StringBuilder();
2213
        while (ex != null){
2214
            if(ex instanceof SQLException){
2215
                builder.append(ex.getLocalizedMessage());
2216
                builder.append("\n");
2217
            }
2218
            ex = ex.getCause();
2219
        }
2220
        return builder.toString();
2221
    }
2222
2223 46971 jjdelcerro
    private void doCopyQueryToCLipboard(FeatureQuery query) {
2224
        ToolsSwingLocator.getToolsSwingManager().putInClipboard(query.toJson().toString());
2225
    }
2226
2227 46536 fdiaz
    private void doShowProperties() {
2228 46585 fdiaz
        try {
2229
            LOGGER.info("Do show properties");
2230
            ToolsSwingManager toolSwingManager = ToolsSwingLocator.getToolsSwingManager();
2231
            SearchParameters params = this.fetch(null);
2232
            StringBuilder msg = new StringBuilder();
2233
            params.isValid(this.getFeatureType(), msg);
2234
            I18nManager i18n = ToolsLocator.getI18nManager();
2235 46971 jjdelcerro
            toolSwingManager.showZoomDialog(
2236
                    this,
2237
                    i18n.getTranslation("_Properties"),
2238
                    params.toString() + "\n" + msg.toString(),
2239
                    false,
2240
                    WindowManager.MODE.DIALOG,
2241
                    ListBuilder.create(
2242
                            new AbstractAction(i18n.getTranslation("_Copy_query")) {
2243
                                @Override
2244
                                public void actionPerformed(ActionEvent e) {
2245
                                    doCopyQueryToCLipboard(params.getQuery());
2246
                                }
2247
                            }
2248
                    )
2249
            );
2250 46585 fdiaz
        } catch (Exception ex) {
2251
            LOGGER.warn("Can't show dialog", ex);
2252
        }
2253 46536 fdiaz
    }
2254 46665 jjdelcerro
2255
    @Override
2256
    public void setPostProcessEnabled(boolean enabled) {
2257
        if (this.initialized) {
2258
            throw new IllegalStateException("Cannot change postProcessEnabled after invoking asJComponent.");
2259
        }
2260
        this.postProcessEnabled = enabled;
2261
    }
2262
2263
    @Override
2264
    public void setGroupByEnabled(boolean enabled) {
2265
        if (this.initialized) {
2266
            throw new IllegalStateException("Cannot change groupByEnabled after invoking asJComponent.");
2267
        }
2268
        this.groupByEnabled = enabled;
2269
    }
2270
2271
    @Override
2272
    public boolean isPostProcessEnabled() {
2273
        return this.postProcessEnabled;
2274
    }
2275
2276
    @Override
2277
    public boolean isGroupByEnabled() {
2278
        return this.groupByEnabled;
2279
    }
2280
2281 47184 jjdelcerro
    private boolean useSelection() {
2282
        boolean x = this.chkUseSelection.isSelected();
2283
        return x;
2284
    }
2285
2286
    private FeatureQuery addSelection(FeatureStore store, FeatureQuery query) {
2287
        query = query.getCopy();
2288
2289
        if( store.isFeatureSelectionEmpty() ) {
2290
            return  query;
2291
        }
2292
        if( store.getMode()!=FeatureStore.MODE_QUERY ) {
2293
            throw new RuntimeException("Use selection not allowed in editing mode");
2294
        }
2295
2296
        FeatureAttributeDescriptor[] pks = store.getDefaultFeatureTypeQuietly().getPrimaryKey();
2297
        if( pks==null ) {
2298
            throw new RuntimeException("Use selection not allowed without primarykey");
2299
        }
2300
        if( pks.length!=1 ) {
2301
            throw new RuntimeException("Use selection not allowed with multifield primarykey");
2302
        }
2303
        ExpressionEvaluatorManager expManager = ExpressionEvaluatorLocator.getExpressionEvaluatorManager();
2304
        ExpressionBuilder expbuilder = expManager.createExpressionBuilder();
2305
2306
        Expression filter = query.getExpressionFilter();
2307
        ExpressionBuilder.Value values = expManager.convertToValue(store.getFeatureSelectionQuietly().referenceIterator());
2308
        if( ExpressionBuilder.isFunction(values, ExpressionBuilder.FUNCTION_TUPLE) ) {
2309
            ((ExpressionBuilder.Function) values).name("");
2310
        }
2311
        String selectionfilter = expbuilder.binaryOperator(
2312
                ExpressionBuilder.OPERATOR_IN,
2313
                expbuilder.variable(pks[0].getName()),
2314
                values
2315
        ).toString();
2316
        StringBuilder builder = new StringBuilder();
2317
        builder.append(selectionfilter);
2318
        if( filter == null ) {
2319
            query.addFilter(builder.toString());
2320
        } else {
2321
            builder.append(" AND (");
2322
            builder.append(filter.getPhrase());
2323
            builder.append(")");
2324
            filter.setPhrase(builder.toString());
2325
        }
2326
        query.retrievesAllAttributes();
2327
        return query;
2328
    }
2329 47417 jjdelcerro
2330
    @Override
2331
    public void addResultPanel(String name, String title, Component component) {
2332
        int index = -1;
2333
        if( this.additionalResultsPanels.containsKey(name) ) {
2334
            index = this.additionalResultsPanels.get(name).getIndex();
2335
        }
2336
        AdditionalResultsPanel panel = new AdditionalResultsPanel(name, title, component, index);
2337
        this.additionalResultsPanels.put(name, panel);
2338
        if( this.initialized ) {
2339
            if( index < 0 ) {
2340
                panel.setIndex(this.tabResults.getTabCount());
2341
                this.tabResults.addTab(panel.getTitle(), panel.asJComponent());
2342
            } else {
2343
                this.tabResults.setComponentAt(index, panel.asJComponent());
2344
                this.tabResults.setTitleAt(index, panel.getTitle());
2345
            }
2346
        }
2347
    }
2348
2349
    @Override
2350
    public void removeResultPanel(String name) {
2351
        int index = -1;
2352
        if( this.additionalResultsPanels.containsKey(name) ) {
2353
            index = this.additionalResultsPanels.get(name).getIndex();
2354
        }
2355
        this.additionalResultsPanels.remove(name);
2356
        if( this.initialized ) {
2357
            this.tabResults.removeTabAt(index);
2358
        }
2359
    }
2360
2361
    @Override
2362
    public DALActionFactory.DALActionContext getSearchActionContext() {
2363
        return new SearchActionContext(this);
2364
    }
2365
2366
    private void fireSearchEvent() {
2367
        ActionEvent e = new ActionEvent(this, 1, "search");
2368
        for (AdditionalResultsPanel additionalResultsPanel : this.additionalResultsPanels.values()) {
2369
            additionalResultsPanel.fireActionEvent(e);
2370
        }
2371
    }
2372
2373
    // https://docs.oracle.com/javase/tutorial/uiswing/components/layeredpane.html
2374 44263 jjdelcerro
}