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 / SearchConditionFieldController.java @ 46723

History | View | Annotate | Download (53.5 KB)

1 44259 jjdelcerro
package org.gvsig.fmap.dal.swing.impl.searchpanel;
2
3
import java.awt.Cursor;
4 44262 jjdelcerro
import java.awt.event.ActionEvent;
5 44259 jjdelcerro
import java.awt.event.ItemEvent;
6
import java.awt.event.ItemListener;
7
import java.awt.event.MouseAdapter;
8
import java.awt.event.MouseEvent;
9 45203 omartinez
import java.text.DateFormat;
10 44259 jjdelcerro
import java.util.ArrayList;
11 44842 omartinez
import java.util.Arrays;
12 45203 omartinez
import java.util.Date;
13 44259 jjdelcerro
import java.util.HashMap;
14
import java.util.List;
15 45203 omartinez
import java.util.Locale;
16 44259 jjdelcerro
import java.util.Map;
17
import java.util.Objects;
18 44829 omartinez
import javax.json.Json;
19
import javax.json.JsonArray;
20
import javax.json.JsonArrayBuilder;
21
import javax.json.JsonObject;
22
import javax.json.JsonObjectBuilder;
23 44259 jjdelcerro
import javax.swing.ComboBoxModel;
24
import javax.swing.DefaultComboBoxModel;
25 44263 jjdelcerro
import javax.swing.ImageIcon;
26 44259 jjdelcerro
import javax.swing.JComboBox;
27
import javax.swing.JLabel;
28 44748 jjdelcerro
import javax.swing.JOptionPane;
29 44262 jjdelcerro
import javax.swing.SwingUtilities;
30 45185 jjdelcerro
import javax.swing.text.JTextComponent;
31 44259 jjdelcerro
import org.apache.commons.lang3.StringUtils;
32
import org.gvsig.expressionevaluator.ExpressionBuilder;
33 44750 jjdelcerro
import org.gvsig.fmap.dal.DALLocator;
34 44262 jjdelcerro
import org.gvsig.fmap.dal.DataManager;
35 44748 jjdelcerro
import org.gvsig.fmap.dal.DataStore;
36 46517 fdiaz
import org.gvsig.fmap.dal.SQLBuilder;
37 44262 jjdelcerro
import org.gvsig.fmap.dal.complements.Search;
38
import org.gvsig.fmap.dal.exception.DataException;
39 44750 jjdelcerro
import org.gvsig.fmap.dal.expressionevaluator.DALExpressionBuilder;
40 44259 jjdelcerro
import org.gvsig.fmap.dal.feature.Feature;
41
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
42 44374 jjdelcerro
import org.gvsig.fmap.dal.feature.FeatureQuery;
43 44259 jjdelcerro
import org.gvsig.fmap.dal.feature.FeatureSet;
44
import org.gvsig.fmap.dal.feature.FeatureStore;
45
import org.gvsig.fmap.dal.feature.FeatureType;
46 44748 jjdelcerro
import org.gvsig.fmap.dal.feature.ForeingKey;
47 46485 fdiaz
import org.gvsig.fmap.dal.swing.DALSwingLocator;
48 44713 jjdelcerro
import org.gvsig.fmap.dal.swing.impl.featuretype.DefaultFeatureAttributeSelectionPanel;
49 46501 jjdelcerro
import static org.gvsig.fmap.dal.swing.impl.searchpanel.SearchConditionPanelSimplified.PANEL_NAME;
50 45326 omartinez
import static org.gvsig.fmap.dal.swing.searchpanel.FeatureStoreSearchPanel.NOT_HANDLE_NULL;
51
import static org.gvsig.fmap.dal.swing.searchpanel.FeatureStoreSearchPanel.NULL_AS_FALSE;
52
import static org.gvsig.fmap.dal.swing.searchpanel.FeatureStoreSearchPanel.NULL_AS_TRUE;
53 45222 omartinez
import org.gvsig.fmap.dal.swing.searchpanel.SearchParameters;
54 44262 jjdelcerro
import org.gvsig.tools.ToolsLocator;
55 44669 jjdelcerro
import org.gvsig.tools.dataTypes.Coercion;
56 44259 jjdelcerro
import org.gvsig.tools.dataTypes.CoercionException;
57 44829 omartinez
import org.gvsig.tools.dataTypes.DataTypeUtils;
58 45185 jjdelcerro
import org.gvsig.tools.dataTypes.DataTypes;
59 45100 jjdelcerro
import org.gvsig.tools.dispose.DisposeUtils;
60 44748 jjdelcerro
import org.gvsig.tools.dynobject.DynField;
61 44259 jjdelcerro
import org.gvsig.tools.exception.BaseException;
62 44688 jjdelcerro
import org.gvsig.tools.i18n.I18nManager;
63 44259 jjdelcerro
import org.gvsig.tools.swing.api.DropDown;
64
import org.gvsig.tools.swing.api.ToolsSwingLocator;
65
import org.gvsig.tools.swing.api.ToolsSwingManager;
66 45185 jjdelcerro
import org.gvsig.tools.swing.api.pickercontroller.DatePickerController;
67 44748 jjdelcerro
import org.gvsig.tools.swing.api.threadsafedialogs.ThreadSafeDialogsManager;
68 44262 jjdelcerro
import org.gvsig.tools.swing.api.windowmanager.Dialog;
69
import org.gvsig.tools.swing.api.windowmanager.WindowManager;
70
import org.gvsig.tools.swing.api.windowmanager.WindowManager_v2;
71 44263 jjdelcerro
import org.gvsig.tools.swing.icontheme.IconTheme;
72 44259 jjdelcerro
import org.gvsig.tools.util.LabeledValue;
73
import org.gvsig.tools.util.LabeledValueImpl;
74
import org.gvsig.tools.visitor.VisitCanceledException;
75
import org.gvsig.tools.visitor.Visitor;
76 44262 jjdelcerro
import org.slf4j.Logger;
77
import org.slf4j.LoggerFactory;
78 44259 jjdelcerro
79
/**
80
 *
81
 * @author jjdelcerro
82
 */
83
@SuppressWarnings("UseSpecificCatch")
84 44713 jjdelcerro
public class SearchConditionFieldController {
85 44259 jjdelcerro
86 45326 omartinez
    private static final Logger LOGGER = LoggerFactory.getLogger(SearchConditionFieldController.class);
87
    private static final Class LOAD_MORE_ELEMENTS = SearchConditionFieldController.class;
88 45331 omartinez
89 45386 jjdelcerro
    private static final int MAXLEN_IN_COMBOS = 70;
90
91 45326 omartinez
    private static class Field extends LabeledValueImpl<String> {
92 44259 jjdelcerro
93 45326 omartinez
        FeatureAttributeDescriptor attrdesc;
94
        private final FeatureStore store;
95
        private final int presentationMode;
96
        private final boolean showStoreName;
97
        private final FeatureAttributeDescriptor[] path;
98 44262 jjdelcerro
99 45326 omartinez
        public Field(FeatureAttributeDescriptor[] path, FeatureStore store, FeatureAttributeDescriptor attrdesc, int presentationMode) {
100
            this(path, store, attrdesc, presentationMode, false);
101
        }
102 44262 jjdelcerro
103 45326 omartinez
        public Field(
104
                FeatureAttributeDescriptor[] path,
105
                FeatureStore store,
106
                FeatureAttributeDescriptor attrdesc,
107
                int presentationMode,
108
                boolean showStoreName
109
        ) {
110
            super(
111 46485 fdiaz
                    DALSwingLocator.getDataSwingManager().getAttributeDescriptorLabel(attrdesc, store.getName()),
112 45326 omartinez
                    attrdesc.getName()
113
            );
114
            this.path = path;
115
            this.store = store;
116
            this.attrdesc = attrdesc;
117
            this.presentationMode = presentationMode;
118
            this.showStoreName = showStoreName;
119
        }
120 44750 jjdelcerro
121 45326 omartinez
        public FeatureAttributeDescriptor[] getPath() {
122
            return this.path;
123
        }
124 44262 jjdelcerro
125 45326 omartinez
        @Override
126
        public String getLabel() {
127 46485 fdiaz
            String theLabel = DALSwingLocator.getDataSwingManager().getAttributeDescriptorLabel(attrdesc, showStoreName ? store.getName() : null);
128 45326 omartinez
            switch (this.presentationMode) {
129
                case Search.OrderedAttribute.TYPE_REGURAL:
130
                    break;
131
                case Search.OrderedAttribute.TYPE_FAVORITE:
132
                    theLabel = "<html><b>" + theLabel + "</b></html>";
133
                    break;
134
                case Search.OrderedAttribute.TYPE_RECENT:
135
                    theLabel = "<html><i><b>" + theLabel + "</b></i></html>";
136
                    break;
137
            }
138
            return theLabel;
139
        }
140 44259 jjdelcerro
141 45326 omartinez
        public FeatureAttributeDescriptor getParentDescriptor() {
142
            int l = this.path.length;
143
            if (l < 2) {
144
                return null;
145
            }
146
            return this.path[l - 2];
147
        }
148 44829 omartinez
149 45326 omartinez
        public FeatureAttributeDescriptor getDescriptor() {
150
            return this.attrdesc;
151
        }
152 44829 omartinez
153 45326 omartinez
        public FeatureStore getFeatureStore() {
154
            return this.store;
155
        }
156
157 44259 jjdelcerro
    }
158 44750 jjdelcerro
159 45326 omartinez
    private FeatureStore store;
160
    private SearchParameters parameters;
161
    private final JLabel lblFields;
162
    private final JLabel lblExtraFields;
163
    private final JLabel lblLogicalOperators;
164
    private final JLabel lblRelationalOperators;
165
    private final JComboBox cboValue;
166
    private final JLabel lblNull;
167
    private Object valueAssigned = null;
168 44829 omartinez
169 45326 omartinez
    private DropDown ddnFields;
170
    private DropDown ddnLogicalOperators;
171
    private DropDown ddnRelationalOperators;
172
    private DropDown ddnNullBehavior;
173 45331 omartinez
174 45326 omartinez
    private LabeledValue[] relationalOperators;
175
    private LabeledValue[] logicalOperators;
176
    private LabeledValue[] nullBehaviors;
177
    private ArrayList<ImageIcon> nullOperatorsIcons;
178 44829 omartinez
179 45326 omartinez
    private final int SIZE_ORDERED_ATTRIBUTES = 20;
180
    private DatePickerController dateController = null;
181 44829 omartinez
182 45326 omartinez
    private int updateValuesTimeLimit;
183
    private int updateValuesFeaturesLimit;
184
    private boolean canHasMoreElements;
185 44259 jjdelcerro
186 45326 omartinez
    public SearchConditionFieldController(
187
            SearchParameters parameters,
188
            FeatureStore store,
189
            JLabel lblFields,
190
            JLabel lblExtraFields,
191
            JLabel lblRelationalOperators,
192
            JComboBox cboValue,
193
            JLabel lblNull,
194
            JLabel lblLogicalOperators
195
    ) {
196
        this.parameters = parameters;
197
        this.store = store;
198
        this.lblFields = lblFields;
199
        this.lblExtraFields = lblExtraFields;
200
        this.lblRelationalOperators = lblRelationalOperators;
201
        this.cboValue = cboValue;
202
        this.lblNull = lblNull;
203
        this.lblLogicalOperators = lblLogicalOperators;
204
        this.updateValuesTimeLimit = 60;
205
        this.updateValuesFeaturesLimit = 1000;
206
        this.canHasMoreElements = false;
207
        this.initComponents();
208
    }
209 45222 omartinez
210 45326 omartinez
    public boolean isAValidRelationOperator(String name) {
211
        for (LabeledValue relationalOperator : relationalOperators) {
212
            if (StringUtils.equalsIgnoreCase(name, (CharSequence) relationalOperator.getValue())) {
213
                return true;
214
            }
215
        }
216
        return false;
217 44748 jjdelcerro
    }
218 44259 jjdelcerro
219 45326 omartinez
    private void initComponents() {
220
        try {
221
            I18nManager i18n = ToolsLocator.getI18nManager();
222
            ToolsSwingManager toolsSwingManager = ToolsSwingLocator.getToolsSwingManager();
223 44259 jjdelcerro
224 45326 omartinez
            relationalOperators = new LabeledValue[]{
225
                new LabeledValueImpl(i18n.getTranslation("_Equals_to"), ExpressionBuilder.OPERATOR_EQ),
226
                new LabeledValueImpl(i18n.getTranslation("_Like_to"), ExpressionBuilder.OPERATOR_ILIKE),
227
                new LabeledValueImpl(i18n.getTranslation("_Not_equals_to"), ExpressionBuilder.OPERATOR_NE),
228
                new LabeledValueImpl(i18n.getTranslation("_Greater_than"), ExpressionBuilder.OPERATOR_GT),
229
                new LabeledValueImpl(i18n.getTranslation("_Greater_or_equal_to"), ExpressionBuilder.OPERATOR_GE),
230
                new LabeledValueImpl(i18n.getTranslation("_Less_than"), ExpressionBuilder.OPERATOR_LT),
231
                new LabeledValueImpl(i18n.getTranslation("_Less_or_equal_to"), ExpressionBuilder.OPERATOR_LE),
232
                new LabeledValueImpl(i18n.getTranslation("_Is_null"), ExpressionBuilder.OPERATOR_IS_NULL),
233
                new LabeledValueImpl(i18n.getTranslation("_Is_not_null"), ExpressionBuilder.OPERATOR_IS_NOT_NULL)
234
            };
235 44259 jjdelcerro
236 45326 omartinez
            logicalOperators = new LabeledValue[]{
237
                new LabeledValueImpl(i18n.getTranslation("_Or"), ExpressionBuilder.OPERATOR_OR),
238
                new LabeledValueImpl(i18n.getTranslation("_And"), ExpressionBuilder.OPERATOR_AND)
239
            };
240 44259 jjdelcerro
241 45326 omartinez
            nullBehaviors = new LabeledValue[]{
242
                new LabeledValueImpl(i18n.getTranslation("_Not_handle_null_values"), NOT_HANDLE_NULL),
243
                new LabeledValueImpl(i18n.getTranslation("_Null_values_as_true"), NULL_AS_TRUE),
244
                new LabeledValueImpl(i18n.getTranslation("_Null_values_as_false"), NULL_AS_FALSE)
245
            };
246 44748 jjdelcerro
247 45326 omartinez
            nullOperatorsIcons = new ArrayList<ImageIcon>();
248
            nullOperatorsIcons.add(ToolsSwingLocator.getIconThemeManager().getCurrent().get("search-nullbehavior-null"));
249
            nullOperatorsIcons.add(ToolsSwingLocator.getIconThemeManager().getCurrent().get("search-nullbehavior-true"));
250
            nullOperatorsIcons.add(ToolsSwingLocator.getIconThemeManager().getCurrent().get("search-nullbehavior-false2"));
251 44748 jjdelcerro
252 45326 omartinez
            this.lblExtraFields.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
253 44688 jjdelcerro
254 45326 omartinez
            this.ddnFields = toolsSwingManager.createDropDown(lblFields);
255
            this.ddnFields.setVisibleDropdownArrow(false);
256
            this.ddnRelationalOperators = toolsSwingManager.createDropDown(lblRelationalOperators);
257
            this.ddnRelationalOperators.setVisibleDropdownArrow(false);
258
            if (lblLogicalOperators != null) {
259
                this.ddnLogicalOperators = toolsSwingManager.createDropDown(lblLogicalOperators);
260
                this.ddnLogicalOperators.setVisibleDropdownArrow(false);
261
            }
262 45331 omartinez
263 45326 omartinez
            DefaultComboBoxModel modelRelationalOperators = new DefaultComboBoxModel();
264
            for (LabeledValue op : relationalOperators) {
265
                modelRelationalOperators.addElement(op);
266
            }
267
            this.ddnRelationalOperators.setModel(modelRelationalOperators);
268
            this.ddnRelationalOperators.addItemListener(new ItemListener() {
269
                @Override
270
                public void itemStateChanged(ItemEvent ie) {
271 45331 omartinez
                    doUpdateControllerByRelationalOperator();
272 45326 omartinez
                }
273
            });
274 45331 omartinez
275 45326 omartinez
            if (this.ddnLogicalOperators != null) {
276
                DefaultComboBoxModel modelLogicalOperators = new DefaultComboBoxModel();
277
                for (LabeledValue op : logicalOperators) {
278
                    modelLogicalOperators.addElement(op);
279
                }
280
                this.ddnLogicalOperators.setModel(modelLogicalOperators);
281
                this.ddnLogicalOperators.setSelectedIndex(1);
282
            }
283 45331 omartinez
284 45326 omartinez
//            this.ddnNullOperators = new DropDownLabelIcon(lblNull);
285
            this.ddnNullBehavior = toolsSwingManager.createDropDownIcon(lblNull);
286
            this.ddnNullBehavior.setVisibleDropdownArrow(false);
287
            DefaultComboBoxModel modelNullOperators = new DefaultComboBoxModel();
288
            for (LabeledValue op : nullBehaviors) {
289
                modelNullOperators.addElement(op);
290
            }
291
            this.ddnNullBehavior.setModel(modelNullOperators);
292
            this.ddnNullBehavior.setIcons(nullOperatorsIcons);
293
            this.ddnNullBehavior.setSelectedIndex(0);
294
            FeatureType featureType = parameters.getFeatureType(store);
295
            Search search = (Search) ToolsLocator.getComplementsManager().get(
296
                    Search.COMPLEMENT_MANE, featureType
297
            );
298
            List<Search.OrderedAttribute> orderedAttributes = search.getOrderedAttributes(
299
                    Search.BASIC_TYPES_FILTER,
300
                    Search.STR_INT_LONG_LABEL_ORDER,
301
                    SIZE_ORDERED_ATTRIBUTES
302
            );
303
            List<ImageIcon> icons = new ArrayList<>();
304 44829 omartinez
//            DataTypesManager dataTypeManager = ToolsLocator.getDataTypesManager();
305 45326 omartinez
            IconTheme iconTheme = ToolsSwingLocator.getIconThemeManager().getCurrent();
306
            DefaultComboBoxModel model = new DefaultComboBoxModel();
307
            for (Search.OrderedAttribute attr : orderedAttributes) {
308
                FeatureAttributeDescriptor attrdesc = attr.getDescriptor();
309
                Field field = new Field(
310
                        new FeatureAttributeDescriptor[]{attrdesc},
311
                        this.store,
312
                        attrdesc,
313
                        attr.getType()
314
                );
315
                model.addElement(field);
316
                String iconName = attrdesc.getDataType().getIconName();
317
                if (iconTheme.exists(iconName)) {
318
                    icons.add(iconTheme.get(iconName));
319
                } else {
320
                    icons.add(null);
321
                }
322
            }
323 44259 jjdelcerro
324 45326 omartinez
            this.ddnFields.setIcons(icons);
325
            this.ddnFields.setModel(model);
326
            this.ddnFields.addItemListener(new ItemListener() {
327
                @Override
328
                public void itemStateChanged(ItemEvent e) {
329
                    if (e.getStateChange() == ItemEvent.SELECTED) {
330
                        doUpdateValuesList();
331
                    }
332
333 45222 omartinez
                }
334 45326 omartinez
            });
335
336
            this.cboValue.addItemListener(new ItemListener() {
337
                @Override
338
                public void itemStateChanged(ItemEvent e) {
339
                    if (e.getStateChange() == ItemEvent.SELECTED) {
340
                        if (cboValue.getSelectedItem() != null && cboValue.getSelectedItem() instanceof LabeledValue) {
341
                            if (Objects.equals(((LabeledValue) cboValue.getSelectedItem()).getValue(), LOAD_MORE_ELEMENTS)) {
342
                                setUpdateValuesLimits(updateValuesTimeLimit + 10, updateValuesFeaturesLimit + 20000);
343
                            }
344
                        }
345
                    }
346
                }
347
            });
348
349
            this.lblExtraFields.addMouseListener(new MouseAdapter() {
350
                @Override
351
                public void mouseClicked(MouseEvent e) {
352
                    doSelectMoreFields();
353
                }
354
            });
355 45331 omartinez
            doUpdateControllerByRelationalOperator();
356 45326 omartinez
//      clear();
357
        } catch (Exception ex) {
358
            throw new RuntimeException(ex);
359 45222 omartinez
        }
360 44829 omartinez
    }
361 44259 jjdelcerro
362 45331 omartinez
    private void doUpdateControllerByRelationalOperator() {
363
        Object item = ((LabeledValue) ddnRelationalOperators.getSelectedItem()).getValue();
364
        if (ExpressionBuilder.OPERATOR_IS_NULL.equals(item) || ExpressionBuilder.OPERATOR_IS_NOT_NULL.equals(item)) {
365
            lblNull.setEnabled(false);
366
            cboValue.setEnabled(false);
367
            cboValue.setSelectedIndex(-1);
368
        } else {
369
            lblNull.setEnabled(true);
370
            cboValue.setEnabled(true);
371
        }
372
373
    }
374
375 45326 omartinez
    private FeatureType getFeatureType() {
376
        try {
377
            return this.store.getDefaultFeatureType();
378
        } catch (DataException ex) {
379
            return null;
380
        }
381 44829 omartinez
    }
382 44748 jjdelcerro
383 45326 omartinez
    private void doSelectMoreFields() {
384 46501 jjdelcerro
        DefaultFeatureAttributeSelectionPanel panel = new DefaultFeatureAttributeSelectionPanel(
385
                store,
386
                parameters.getFeatureType(store),
387
                parameters.getQuery()
388
        );
389 45326 omartinez
        WindowManager_v2 winManager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
390
        final Dialog dialog = winManager.createDialog(
391
                panel,
392
                "Select attribute",
393
                null,
394
                WindowManager_v2.BUTTONS_OK_CANCEL
395 44829 omartinez
        );
396 45326 omartinez
        dialog.addActionListener((ActionEvent e) -> {
397
            if (dialog.getAction() == WindowManager_v2.BUTTONS_OK) {
398
                doAddAndSelect(
399
                        panel.getSelectedStore(),
400
                        panel.getSelectedAttributeDescriptor(),
401
                        panel.getSelectedPath()
402
                );
403
            }
404
        });
405
        dialog.show(WindowManager.MODE.DIALOG);
406 44748 jjdelcerro
407 45222 omartinez
    }
408
409 45326 omartinez
    private void doAddAndSelect(FeatureStore theStore, FeatureAttributeDescriptor attrdesc, FeatureAttributeDescriptor[] path) {
410
        ThreadSafeDialogsManager dialogManager = ToolsSwingLocator.getThreadSafeDialogsManager();
411
        I18nManager i18n = ToolsLocator.getI18nManager();
412
        DefaultComboBoxModel<Field> model = (DefaultComboBoxModel) this.ddnFields.getModel();
413
        if (attrdesc == null) {
414
            dialogManager.messageDialog(
415
                    i18n.getTranslation("_It_is_not_supported_to_search_through_this_field") + "\n"
416
                    + i18n.getTranslation("_Field_not_found"),
417
                    "_Warning",
418
                    JOptionPane.WARNING_MESSAGE
419
            );
420
            return;
421
        }
422
423
        for (int i = 0; i < model.getSize(); i++) {
424
            Field field = model.getElementAt(i);
425
            FeatureAttributeDescriptor attrdescN = field.getDescriptor();
426 46171 omartinez
            if (theStore!=null && attrdescN.getStore()!=null && isTheSameStore(theStore, attrdescN.getStore())
427 45326 omartinez
                    && StringUtils.equalsIgnoreCase(attrdesc.getName(), attrdescN.getName())) {
428
                this.setAttribute(i);
429
                return;
430 45084 jjdelcerro
            }
431 45326 omartinez
        }
432
        Field field = new Field(
433
                path,
434
                theStore,
435
                attrdesc,
436
                Search.OrderedAttribute.TYPE_REGURAL,
437
                !isTheSameStore(store, theStore)
438
        );
439
        if (field.getPath().length > 2) {
440
            dialogManager.messageDialog(
441
                    i18n.getTranslation("_It_is_not_supported_to_search_through_this_field") + "\n"
442
                    + i18n.getTranslation("_To_many_links"),
443
                    "_Warning",
444
                    JOptionPane.WARNING_MESSAGE
445
            );
446
            return;
447
        }
448
        FeatureAttributeDescriptor parentDescriptor = field.getParentDescriptor();
449
        if (parentDescriptor != null) {
450
            switch (parentDescriptor.getRelationType()) {
451
                case DynField.RELATION_TYPE_AGGREGATE:
452
                case DynField.RELATION_TYPE_COMPOSITION:
453
                    if (getForeingKeyName(field.getFeatureStore(), this.store) == null) {
454
                        dialogManager.messageDialog(
455
                                "It not supported to search through this field." + "\n"
456
                                + "The link field was not found.",
457
                                "_Warning",
458
                                JOptionPane.WARNING_MESSAGE
459
                        );
460
                        return;
461
                    }
462
                    if (getPrimaryKeyName(this.store) == null) {
463
                        dialogManager.messageDialog(
464
                                "It not supported to search through this field." + "\n"
465
                                + "A simple primary key was not found.",
466
                                "_Warning",
467
                                JOptionPane.WARNING_MESSAGE
468
                        );
469
                        return;
470
                    }
471 45084 jjdelcerro
            }
472 44748 jjdelcerro
        }
473 45326 omartinez
        model.addElement(field);
474
        IconTheme iconTheme = ToolsSwingLocator.getIconThemeManager().getCurrent();
475
        this.ddnFields.getIcons().add(iconTheme.get(attrdesc.getDataType().getIconName()));
476
        this.setAttribute(model.getSize() - 1);
477 44829 omartinez
    }
478 44262 jjdelcerro
479 45326 omartinez
    public void clear() {
480
        this.ddnRelationalOperators.setSelectedIndex(0);
481
        if (this.ddnLogicalOperators != null) {
482
            this.ddnLogicalOperators.setSelectedIndex(1);
483 45185 jjdelcerro
        }
484 45326 omartinez
        this.cboValue.setSelectedIndex(-1);
485
        this.ddnNullBehavior.setSelectedIndex(0);
486 45331 omartinez
        doUpdateControllerByRelationalOperator();
487 45185 jjdelcerro
    }
488 44262 jjdelcerro
489 46505 fdiaz
    private String lastNameInUpdateValuesList = null;
490
    private int lastUpdateValuesFeaturesLimit = -1;
491
    private int lastUpdateValuesTimeLimit = -1;
492
493 45326 omartinez
    private void doUpdateValuesList() {
494
        final Field field = (Field) this.ddnFields.getSelectedItem();
495
        if (field == null) {
496
            return;
497 44855 jjdelcerro
        }
498 45326 omartinez
        FeatureAttributeDescriptor descriptor = field.getDescriptor();
499 46505 fdiaz
        if(StringUtils.equalsIgnoreCase(lastNameInUpdateValuesList, descriptor.getName()) &&
500
                updateValuesFeaturesLimit == lastUpdateValuesFeaturesLimit &&
501
                updateValuesTimeLimit == lastUpdateValuesTimeLimit
502
                ){
503
            return;
504
        }
505
        lastNameInUpdateValuesList = descriptor.getName();
506
        lastUpdateValuesFeaturesLimit = updateValuesFeaturesLimit;
507
        lastUpdateValuesTimeLimit = updateValuesTimeLimit;
508
509 45326 omartinez
        if (descriptor.getType() == DataTypes.DATE) {
510
            if (this.dateController == null) {
511
                this.dateController = ToolsSwingLocator.getToolsSwingManager().createDatePickerController(
512
                        (JTextComponent) this.cboValue.getEditor().getEditorComponent(),
513
                        null
514
                );
515 44855 jjdelcerro
            }
516 45326 omartinez
        } else {
517
            if (this.dateController != null) {
518
                this.dateController.uninstall();
519
                this.dateController = null;
520 45203 omartinez
            }
521 45326 omartinez
        }
522 44748 jjdelcerro
523 45326 omartinez
        final List<Object> values = new ArrayList<>();
524
        final DefaultComboBoxModel model = new DefaultComboBoxModel();
525
        final FeatureStore theStore = field.getFeatureStore();
526
        final FeatureQuery query;
527 46517 fdiaz
        query = theStore.createFeatureQuery();
528 45326 omartinez
        query.addAttributeName(field.getDescriptor().getName());
529
        query.setFilter("");
530 46586 fdiaz
        query.getExtraColumns().copyFrom(this.parameters.getQuery().getExtraColumns());
531 45326 omartinez
        query.setLimit(updateValuesFeaturesLimit);
532
        query.getGroupByColumns().clear();
533
        query.getAggregateFunctions().clear();
534
        Thread th = new Thread(new Runnable() {
535
            @Override
536
            public void run() {
537
                FeatureSet set = null;
538
                try {
539
                    canHasMoreElements = false;
540
                    set = theStore.getFeatureSet(query);
541
                    if (set.size() >= updateValuesFeaturesLimit) {
542
                        canHasMoreElements = true;
543
                    }
544
                    final long timeLimit = System.currentTimeMillis() + updateValuesTimeLimit * 1000;
545
                    set.accept(new Visitor() {
546
                        @Override
547
                        public void visit(Object o) throws VisitCanceledException, BaseException {
548
                            Object value = ((Feature) o).get(field.getDescriptor().getName());
549 45331 omartinez
                            if (value!=null && !values.contains(value)) {
550 45326 omartinez
                                values.add(value);
551
                            }
552
                            if (System.currentTimeMillis() > timeLimit) {
553
                                canHasMoreElements = true;
554
                                throw new VisitCanceledException();
555
                            }
556
                            if (values.size() > 1000) {
557
                                canHasMoreElements = true;
558
                                throw new VisitCanceledException();
559
                            }
560
                        }
561
                    });
562
                } catch (VisitCanceledException ex) {
563
                    canHasMoreElements = true;
564
                } catch (Exception ex) {
565
                    LOGGER.warn("Can't update list of values of '" + field.getLabel() + "'.", ex);
566
                } finally {
567
                    DisposeUtils.disposeQuietly(set);
568
                }
569
                List<LabeledValue> elements = new ArrayList<>();
570
                if (!values.isEmpty()) {
571
                    LabeledValue[] availableValues = field.getDescriptor().getAvailableValues();
572
                    Map<String, String> availableValuesMap = new HashMap<>();
573
                    if (availableValues != null) {
574
                        for (LabeledValue availableValue : availableValues) {
575
                            availableValuesMap.put(
576
                                    Objects.toString(availableValue.getValue()),
577
                                    availableValue.getLabel()
578
                            );
579
                        }
580
                    }
581 45386 jjdelcerro
                    elements.add(new LabeledValueImpl("", null, MAXLEN_IN_COMBOS));
582 45326 omartinez
                    for (Object value : values) {
583
                        String key;
584 45329 omartinez
                        key = DataTypeUtils.toString(value);
585 45326 omartinez
                        String label = availableValuesMap.getOrDefault(key, key);
586 45386 jjdelcerro
                        elements.add(new LabeledValueImpl(label, value, MAXLEN_IN_COMBOS));
587 45326 omartinez
                    }
588
                    elements.sort(null);
589
590
                }
591
                for (LabeledValue element : elements) {
592
                    model.addElement(element);
593
                }
594
                if (canHasMoreElements) {
595
                    model.addElement(new LabeledValueImpl("...", LOAD_MORE_ELEMENTS));
596
                }
597
                SwingUtilities.invokeLater(new Runnable() {
598
                    @Override
599
                    public void run() {
600
                        setEnabled(false);
601
                        cboValue.setModel(model);
602
                        if (valueAssigned != null) {
603
                            cboValue.setSelectedItem(valueAssigned);
604
                            valueAssigned = null;
605
                        }
606
                        setEnabled(true);
607
                    }
608
                });
609 44829 omartinez
            }
610
        });
611 45326 omartinez
        th.start();
612
    }
613 44829 omartinez
614 45326 omartinez
    public void setEnabled(boolean enabled) {
615
        ddnFields.setEnabled(enabled);
616
        if (ddnLogicalOperators != null) {
617
            ddnLogicalOperators.setEnabled(enabled);
618
        }
619
        ddnRelationalOperators.setEnabled(enabled);
620
        lblExtraFields.setEnabled(enabled);
621
        cboValue.setEnabled(enabled);
622 45331 omartinez
        doUpdateControllerByRelationalOperator();
623 45326 omartinez
    }
624 44829 omartinez
625 45326 omartinez
    public String getRelationalOperator() {
626
        LabeledValue<String> op = (LabeledValue) this.ddnRelationalOperators.getSelectedItem();
627
        if (op == null) {
628
            return null;
629
        }
630
        return op.getValue();
631 44262 jjdelcerro
    }
632
633 45326 omartinez
    public int setRelationalOperator(String name) {
634
        int n = 0;
635
        for (LabeledValue relationalOperator : relationalOperators) {
636
            if (StringUtils.equalsIgnoreCase(name, (CharSequence) relationalOperator.getValue())) {
637
                break;
638
            }
639
            n++;
640
        }
641
        if (this.relationalOperators.length <= n) {
642
            return -1;
643
        }
644
        this.ddnRelationalOperators.setSelectedIndex(n);
645 45331 omartinez
        doUpdateControllerByRelationalOperator();
646 45326 omartinez
        return n;
647 44259 jjdelcerro
    }
648 44262 jjdelcerro
649 45326 omartinez
    public String getLogicalOperator() {
650
        if (this.ddnLogicalOperators == null) {
651
            return null;
652
        }
653
        LabeledValue<String> rel = (LabeledValue) this.ddnLogicalOperators.getSelectedItem();
654
        if (rel == null) {
655
            return null;
656
        }
657
        return rel.getValue();
658 44748 jjdelcerro
    }
659 44262 jjdelcerro
660 45326 omartinez
    public void setLogicalOperator(String operator) {
661
        if (this.ddnLogicalOperators == null) {
662
            return;
663
        }
664
        ComboBoxModel model = this.ddnLogicalOperators.getModel();
665
        for (int i = 0; i < model.getSize(); i++) {
666
            LabeledValue modelValue = (LabeledValue) model.getElementAt(i);
667
            String value = (String) modelValue.getValue();
668
            if (StringUtils.equals(value, operator)) {
669
                this.ddnLogicalOperators.setSelectedIndex(i);
670
                break;
671
            }
672
        }
673 44829 omartinez
    }
674 44262 jjdelcerro
675 45326 omartinez
    public Object getValue() {
676
        final Field field = (Field) this.ddnFields.getSelectedItem();
677
        if (field == null) {
678
            return null;
679
        }
680
        Object v;
681
        if (this.dateController == null) {
682
            v = this.cboValue.getSelectedItem();
683
        } else {
684
            v = this.dateController.get();
685
        }
686
        if (v == null) {
687
            return null;
688
        }
689
        if (v instanceof LabeledValue) {
690
            v = ((LabeledValue) v).getValue();
691 45793 jjdelcerro
            if (v == null || v == LOAD_MORE_ELEMENTS) {
692 45326 omartinez
                return null;
693
            }
694
        }
695
        if (v instanceof CharSequence) {
696
            if (StringUtils.isBlank((CharSequence) v)) {
697
                return null;
698
            }
699
        }
700
        Coercion coercion = field.getDescriptor().getDataType().getCoercion();
701
        try {
702
            return coercion.coerce(v);
703
        } catch (CoercionException ex) {
704
            return null;
705
        }
706 44829 omartinez
    }
707 44748 jjdelcerro
708 45274 omartinez
    public void setValue(Object value) {
709
        //this.cboValue.setSelectedItem(value);
710
        SwingUtilities.invokeLater(new Runnable() {
711
            @Override
712
            public void run() {
713 45326 omartinez
                DefaultComboBoxModel model = (DefaultComboBoxModel) cboValue.getModel();
714
                for (int i = 0; i < model.getSize(); i++) {
715
                    Object item = model.getElementAt(i);
716 45274 omartinez
                    if (item.equals(value)) {
717 45326 omartinez
                        cboValue.setSelectedIndex(i);
718
                        valueAssigned = value;
719
                        return;
720
                    }
721 45274 omartinez
                }
722 46517 fdiaz
                // si no lo encuentra en el modelo lo a?ade
723 45326 omartinez
                final Field field = (Field) ddnFields.getSelectedItem();
724
                if (field == null) {
725
                    return;
726
                } else {
727
                    LabeledValue[] availableValues = field.getDescriptor().getAvailableValues();
728
                    Map<String, String> availableValuesMap = new HashMap<>();
729
                    if (availableValues != null) {
730
                        for (LabeledValue availableValue : availableValues) {
731
                            availableValuesMap.put(
732
                                    Objects.toString(availableValue.getValue()),
733
                                    availableValue.getLabel()
734
                            );
735
                        }
736
                    }
737
                    String key;
738
                    if (value instanceof Date) {
739
                        DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
740
                        df.setLenient(false);
741
                        key = df.format(value);
742
                    } else {
743
                        key = Objects.toString(value);
744
                    }
745
                    String label = availableValuesMap.getOrDefault(key, key);
746
                    LabeledValueImpl newItem = new LabeledValueImpl(label, value);
747
                    model.addElement(newItem);
748
                    cboValue.setSelectedItem(newItem);
749
                    valueAssigned = newItem;
750
                }
751 45274 omartinez
            }
752
        });
753
    }
754 44855 jjdelcerro
755 45326 omartinez
    private Field getCurrentField() {
756
        final Field field = (Field) this.ddnFields.getSelectedItem();
757
        return field;
758 44262 jjdelcerro
    }
759
760 45326 omartinez
    public int setAttribute(String name) {
761 44829 omartinez
        ComboBoxModel<Field> model = this.ddnFields.getModel();
762
        for (int i = 0; i < model.getSize(); i++) {
763 45326 omartinez
            Field x = model.getElementAt(i);
764
            if (StringUtils.equalsIgnoreCase(name, x.getValue())) {
765
                this.setAttribute(i);
766
                return i;
767
            }
768 44829 omartinez
        }
769 45326 omartinez
        this.setAttribute(-1);
770
        return -1;
771
    }
772 44842 omartinez
773 45326 omartinez
    public void setAttribute(int index) {
774
        try {
775
            this.ddnFields.setSelectedIndex(index);
776
        } catch (Exception ex) {
777
            this.ddnFields.setSelectedIndex(-1);
778 44829 omartinez
        }
779 45326 omartinez
        doUpdateValuesList();
780 44259 jjdelcerro
    }
781 44842 omartinez
782 45326 omartinez
    public int setAttributePath(String[][] pathNames) {
783
        // [[attributeName, storeName],...]
784
        try {
785
            if (pathNames.length == 1) {
786
                String[] path = pathNames[pathNames.length - 1];
787
                String name = path[0];
788
                int index = this.setAttribute(name);
789
                if (index == -1) {
790
                    try {
791 46536 fdiaz
                        FeatureAttributeDescriptor attrDescriptor = store.getDefaultFeatureType().getAttributeDescriptorFromAll(name);
792 45326 omartinez
                        if (attrDescriptor == null) {
793 46536 fdiaz
                            FeatureQuery query = this.parameters.getQuery();
794
                            if(query != null){
795
                                attrDescriptor = query.getExtraColumns().get(name);
796
                            }
797
                        }
798
                        if (attrDescriptor == null) {
799 45326 omartinez
                            I18nManager i18n = ToolsLocator.getI18nManager();
800
                            ThreadSafeDialogsManager dialogManager = ToolsSwingLocator.getThreadSafeDialogsManager();
801
                            dialogManager.messageDialog(
802
                                    i18n.getTranslation("_It_is_not_supported_to_search_through_this_field") + ":\n " + name + "\n"
803
                                    + i18n.getTranslation("_Field_not_found_in_this_table"),
804
                                    "_Warning",
805
                                    JOptionPane.WARNING_MESSAGE
806
                            );
807
                            this.cboValue.setModel(new DefaultComboBoxModel());
808
                        } else {
809 46536 fdiaz
                            FeatureAttributeDescriptor[] attributePath = new FeatureAttributeDescriptor[]{attrDescriptor};
810
                            doAddAndSelect(store, attrDescriptor, attributePath);
811 45326 omartinez
                        }
812
                    } catch (Exception ex) {
813
                        LOGGER.warn("Not able to set single path into controller", ex);
814
                        return -1;
815
                    }
816
                }
817
                return index;
818
            } else {
819
                ComboBoxModel<Field> model = this.ddnFields.getModel();
820
                String[] singleArrayPathNameDescriptors = new String[pathNames.length];
821
                for (int i = 0; i < pathNames.length; i++) {
822
                    singleArrayPathNameDescriptors[i] = pathNames[i][0];
823
                }
824
                // check the drop
825
                for (int i = 0; i < model.getSize(); i++) {
826
                    Field x = model.getElementAt(i);
827
                    String[] arrayDescriptors = new String[x.getPath().length];
828
                    FeatureAttributeDescriptor[] path = x.getPath();
829
                    for (int j = 0; j < path.length; j++) {
830
                        arrayDescriptors[j] = path[j].getName();
831
                    }
832
                    if (Arrays.equals(singleArrayPathNameDescriptors, arrayDescriptors)) {
833
                        this.setAttribute(i);
834
                        return i;
835
                    }
836
                }
837
                // if not, addit to the drop
838
                DataManager dataManager = DALLocator.getDataManager();
839
                String tableName = pathNames[pathNames.length - 1][1]; // del ultimo path, coger el nombre tabla
840
                FeatureStore theStore = (FeatureStore) dataManager.getStoresRepository().getStore(tableName);
841
                String attributeName = pathNames[pathNames.length - 1][0]; // del ultimo path, coger el nombre attribute
842
                if (theStore != null) {
843
                    FeatureAttributeDescriptor attr;
844
                    try {
845
                        attr = theStore.getDefaultFeatureType().getAttributeDescriptor(attributeName);
846
                        FeatureAttributeDescriptor[] attributePath = new FeatureAttributeDescriptor[2];
847
                        String firstAttrName = pathNames[0][0];
848
                        FeatureAttributeDescriptor firstAttr = store.getDefaultFeatureType().getAttributeDescriptor(firstAttrName);
849
                        attributePath[0] = firstAttr;
850 44842 omartinez
851 45326 omartinez
                        attributePath[1] = attr;
852
                        doAddAndSelect(theStore, attr, attributePath);
853
                        return SIZE_ORDERED_ATTRIBUTES - 1;
854
                    } catch (Exception ex) {
855
                        LOGGER.warn("Not able to set foreign path into controller", ex);
856
                    }
857 44842 omartinez
858 45326 omartinez
                }
859
860
            }
861
        } catch (Exception ex) {
862
            LOGGER.warn("Controller not set.", ex);
863 44829 omartinez
        }
864 45326 omartinez
        this.setAttribute(-1);
865
        return -1;
866 44748 jjdelcerro
    }
867 44842 omartinez
868 45326 omartinez
    private boolean isTheSameStore(DataStore store1, DataStore store2) {
869
        String store1FullName = store1.getFullName();
870
        String store2FullName = store2.getFullName();
871
        return StringUtils.equalsIgnoreCase(store1FullName, store2FullName);
872 44829 omartinez
    }
873 45326 omartinez
874
    private String getPrimaryKeyName(FeatureStore store) {
875
        try {
876
            FeatureAttributeDescriptor[] pk = store.getDefaultFeatureType().getPrimaryKey();
877
            if (pk == null || pk.length != 1) {
878
                return null;
879
            }
880
            return pk[0].getName();
881
        } catch (DataException ex) {
882
            return null;
883
        }
884 44292 jjdelcerro
    }
885 45326 omartinez
886
    private String getForeingKeyName(FeatureStore store, FeatureStore foreingStore) {
887
        try {
888
            for (FeatureAttributeDescriptor descriptor : store.getDefaultFeatureType()) {
889
                if (descriptor.isForeingKey()) {
890
                    ForeingKey foreingKey = descriptor.getForeingKey();
891
                    if (isTheSameStore(foreingStore, foreingKey.getFeatureStore(null))) {
892
                        return descriptor.getName();
893
                    }
894
                }
895
            }
896
        } catch (DataException ex) {
897
            return null;
898
        }
899
        return null;
900 44259 jjdelcerro
    }
901 45326 omartinez
902
    public boolean isValid(StringBuilder message) {
903 44829 omartinez
        try {
904 45326 omartinez
            Object value = this.getValue();
905
            if (value == null) {
906
                return true;
907
            }
908
            Field field = this.getCurrentField();
909
            if (field == null) {
910
                return true;
911
            }
912
            if (field.getPath().length > 2) {
913
                message.append("Invalid field '").append(field.getLabel()).append("'.\n");
914
                return false;
915
            }
916
            FeatureAttributeDescriptor descriptor = field.getDescriptor();
917
            switch (this.getRelationalOperator()) {
918
                case ExpressionBuilder.OPERATOR_EQ:
919
                case ExpressionBuilder.OPERATOR_NE:
920
                case ExpressionBuilder.OPERATOR_GT:
921
                case ExpressionBuilder.OPERATOR_GE:
922
                case ExpressionBuilder.OPERATOR_LT:
923
                case ExpressionBuilder.OPERATOR_LE:
924
        try {
925
                    descriptor.getDataType().coerce(value);
926
                } catch (CoercionException ex) {
927
                    message.append("Invalid value '")
928
                            .append(Objects.toString(value))
929
                            .append("' for field '")
930
                            .append(descriptor.getLabel())
931
                            .append("'.");
932
                    message.append("\n");
933
                    message.append(ex.getMessage());
934
                    message.append("\n");
935
                    return false;
936
                }
937
                break;
938 44829 omartinez
939 45326 omartinez
                default:
940
                case ExpressionBuilder.OPERATOR_ILIKE:
941
                    break;
942
            }
943
            return true;
944
        } catch (Exception ex) {
945
            message.append("Invalid values '").append(ex.toString());
946
            return false;
947
        }
948 44748 jjdelcerro
    }
949 44262 jjdelcerro
950 45326 omartinez
    public ExpressionBuilder.Value getFilter() {
951
        ExpressionBuilder.Value filter = null;
952 44748 jjdelcerro
953 45326 omartinez
        Object value = this.getValue();
954 45331 omartinez
        if (value == null
955
                && this.getRelationalOperator() != ExpressionBuilder.OPERATOR_IS_NULL
956
                && this.getRelationalOperator() != ExpressionBuilder.OPERATOR_IS_NOT_NULL) {
957 45326 omartinez
            return null;
958
        }
959
        Field field = this.getCurrentField();
960
        if (field == null) {
961
            return null;
962
        }
963
        if (field.getPath().length > 2) {
964
            // No soportado
965
            return null;
966
        }
967
        DataManager dataManager = DALLocator.getDataManager();
968
        DALExpressionBuilder builder = dataManager.createDALExpressionBuilder();
969
        FeatureAttributeDescriptor parentDescriptor = field.getParentDescriptor();
970
        FeatureAttributeDescriptor descriptor = field.getDescriptor();
971 44748 jjdelcerro
972 45326 omartinez
        ExpressionBuilder.Constant value_constant = null;
973 44262 jjdelcerro
974 45326 omartinez
        switch (this.getRelationalOperator()) {
975 45331 omartinez
            case ExpressionBuilder.OPERATOR_IS_NULL:
976
                filter = getFilterForOperatorNull(parentDescriptor, descriptor, builder, field);
977
                return filter;
978
            case ExpressionBuilder.OPERATOR_IS_NOT_NULL:
979
                filter = getFilterForOperatorNotNull(parentDescriptor, descriptor, builder, field);
980
                return filter;
981 45326 omartinez
            case ExpressionBuilder.OPERATOR_EQ:
982
            case ExpressionBuilder.OPERATOR_NE:
983
            case ExpressionBuilder.OPERATOR_GT:
984
            case ExpressionBuilder.OPERATOR_GE:
985
            case ExpressionBuilder.OPERATOR_LT:
986
            case ExpressionBuilder.OPERATOR_LE:
987 44829 omartinez
        try {
988 45326 omartinez
                value_constant = builder.expression().constant(
989
                        descriptor.getDataType().coerce(value)
990
                );
991
            } catch (CoercionException ex) {
992
                return null;
993
            }
994
            break;
995 44262 jjdelcerro
996 45326 omartinez
            default:
997
            case ExpressionBuilder.OPERATOR_ILIKE:
998
                value_constant = builder.expression().constant(value);
999
                break;
1000
        }
1001 44750 jjdelcerro
1002 45326 omartinez
        if (parentDescriptor == null) {
1003 45331 omartinez
            // Se busca en campos de la misma tabla.
1004
            filter = builder.expression().binaryOperator(
1005
                    this.getRelationalOperator(),
1006
                    builder.expression().column(this.store.getName(), descriptor.getName()),
1007
                    value_constant
1008
            );
1009 44750 jjdelcerro
1010 45331 omartinez
            ExpressionBuilder.Value nullValue = builder.expression().column(this.store.getName(), descriptor.getName());
1011
            filter = addNullBehavior(builder, filter, nullValue);
1012 44750 jjdelcerro
1013 45326 omartinez
        } else {
1014
            // Se busca en campos de una tabla relacionada.
1015
            switch (parentDescriptor.getRelationType()) {
1016
                case DynField.RELATION_TYPE_COLLABORATION:
1017
                case DynField.RELATION_TYPE_IDENTITY:
1018 45331 omartinez
                    filter = builder.expression().binaryOperator(
1019
                            this.getRelationalOperator(),
1020
                            builder.foreing_value(
1021 45326 omartinez
                                    parentDescriptor.getName(),
1022
                                    descriptor.getName()
1023 45331 omartinez
                            ),
1024
                            value_constant
1025
                    );
1026
                    ExpressionBuilder.Value nullValue = builder.foreing_value(
1027
                            parentDescriptor.getName(),
1028
                            descriptor.getName()
1029
                    );
1030
                    filter = addNullBehavior(builder, filter, nullValue);
1031 45326 omartinez
                    break;
1032 44842 omartinez
1033 45326 omartinez
                case DynField.RELATION_TYPE_AGGREGATE:
1034
                case DynField.RELATION_TYPE_COMPOSITION:
1035
                    ExpressionBuilder.Value op_composition = null;
1036 45331 omartinez
                    op_composition = builder.expression().binaryOperator(
1037
                            this.getRelationalOperator(),
1038
                            builder.expression().column(
1039 45326 omartinez
                                    field.getFeatureStore().getName(),
1040
                                    descriptor.getName()
1041 45331 omartinez
                            ),
1042
                            value_constant
1043
                    );
1044
                    ExpressionBuilder.Value null_value = builder.expression().column(
1045
                            field.getFeatureStore().getName(),
1046
                            descriptor.getName()
1047
                    );
1048 45352 omartinez
                    op_composition = addNullBehavior(builder, op_composition, null_value);
1049 44842 omartinez
1050 46517 fdiaz
                    filter = buildExists(builder, field, op_composition);
1051 45326 omartinez
                    break;
1052
            }
1053
        }
1054 45331 omartinez
1055 45326 omartinez
        filter = builder.expression().group(filter);
1056
        return filter;
1057 44855 jjdelcerro
    }
1058 44767 jjdelcerro
1059 46517 fdiaz
    private ExpressionBuilder.Value buildExists(DALExpressionBuilder builder, Field field, ExpressionBuilder.Value op_composition) {
1060
        ExpressionBuilder.Value filter;
1061
        SQLBuilder.SelectBuilder select = builder.select();
1062
        select.from().table().name(field.getFeatureStore().getName());
1063
        //select.column().name(parentDescriptor.getFeatureType().getPrimaryKey()[0].getName());
1064
        select.column().value(builder.expression().constant(1));
1065
        select.limit(1);
1066
        select.where().value(
1067
                builder.expression().and(
1068
                        builder.expression().eq(
1069
                                builder.expression().column(
1070
                                        field.getFeatureStore().getName(),
1071
                                        getForeingKeyName(field.getFeatureStore(), this.store)
1072
                                ),
1073
                                builder.expression().column(
1074
                                        this.store.getName(),
1075
                                        getPrimaryKeyName(this.store)
1076
                                )
1077
                        ),
1078
                        op_composition
1079
                )
1080
        );
1081
        filter = builder.exists(select);
1082
        return filter;
1083
    }
1084
1085 45326 omartinez
    public JsonObject toJson() {
1086
        JsonObjectBuilder fieldBuilder = Json.createObjectBuilder();
1087 44750 jjdelcerro
1088 45326 omartinez
        JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
1089 46536 fdiaz
        Field currentField = this.getCurrentField();
1090
//        if(currentField == null){
1091
//            return null;
1092
//        }
1093
        FeatureAttributeDescriptor[] path = currentField.getPath();
1094 46358 fdiaz
        for (int i = 0; i < path.length; i++) {
1095
            FeatureAttributeDescriptor featureAttributeDescriptor = path[i];
1096 45326 omartinez
            JsonArrayBuilder pathArray = Json.createArrayBuilder();
1097 44767 jjdelcerro
1098 45326 omartinez
            //first value: name field
1099
            String fieldName = featureAttributeDescriptor.getName();
1100
            pathArray.add(fieldName);
1101
            //second value: name store
1102 46358 fdiaz
            if(i==0){
1103
                pathArray.add(this.store.getName());
1104
            } else {
1105
                FeatureType featureType = featureAttributeDescriptor.getFeatureType();
1106
                String storeName = featureType.getStore().getName();
1107
                pathArray.add(storeName);
1108
            }
1109 45326 omartinez
            arrayBuilder.add(pathArray.build());
1110
        }
1111
        String relational = this.getRelationalOperator();
1112
        Object value = this.getValue();
1113
        String strValue = DataTypeUtils.toString(value);
1114
        String logical = this.getLogicalOperator();
1115
1116
        fieldBuilder.add("fieldPath", arrayBuilder.build());
1117
        fieldBuilder.add("relational", relational);
1118
        if (!StringUtils.isEmpty(strValue)) {
1119
            fieldBuilder.add("strValue", strValue);
1120
        }
1121
        if (!StringUtils.isEmpty(logical)) {
1122
            fieldBuilder.add("logical", logical);
1123
        }
1124
        int nullBehavior = this.getNullBehavior();
1125
        fieldBuilder.add("nullBehavior", nullBehavior);
1126
        return fieldBuilder.build();
1127 44855 jjdelcerro
    }
1128 46501 jjdelcerro
1129
    public void put(SearchParameters params, int index) {
1130
        this.parameters = params;
1131
        Map<String, JsonObject> values = params.getValues();
1132
        if( values == null ) {
1133
            return;
1134
        }
1135
        JsonObject panelState = values.getOrDefault(PANEL_NAME, null);
1136
        if( panelState == null ) {
1137
            return;
1138
        }
1139
        String name = DataTypeUtils.toString(index);
1140
        this.fromJson(panelState.getJsonObject(name));
1141
    }
1142
1143 45326 omartinez
    public void fromJson(JsonObject jsonState) {
1144
        if (jsonState == null) {
1145
            return;
1146
        }
1147 44767 jjdelcerro
1148 45326 omartinez
        JsonArray fieldPath = jsonState.getJsonArray("fieldPath");
1149
1150
        // array of arrays
1151
        String[][] arrayNew = new String[fieldPath.size()][2];
1152
        for (int i = 0; i < fieldPath.size(); i++) {
1153
            String[] arrayField = new String[2];
1154
            arrayField[0] = fieldPath.getJsonArray(i).getString(0);
1155
            arrayField[1] = fieldPath.getJsonArray(i).getString(1);
1156
            arrayNew[i] = arrayField;
1157
        }
1158
        this.setAttributePath(arrayNew);  //usar el doAddAndSelect
1159
1160
        String relational = jsonState.getString("relational");
1161
        this.setRelationalOperator(relational);
1162
1163
        if (jsonState.containsKey("strValue")) {
1164
            String strValue = jsonState.getString("strValue");
1165 45280 omartinez
//        SwingUtilities.invokeLater(new Runnable() {
1166
//            @Override
1167
//            public void run() {
1168 45326 omartinez
            setValue(strValue);
1169 45280 omartinez
//            }
1170
//        });
1171 45326 omartinez
        }
1172
        if (jsonState.containsKey("logical")) {
1173
            String logical = jsonState.getString("logical");
1174
            this.setLogicalOperator(logical);
1175
        }
1176
        if (jsonState.containsKey("nullBehavior")) {
1177
            int nullBehavior = jsonState.getInt("nullBehavior");
1178
            this.setNullBehavior(nullBehavior);
1179
        }
1180
1181 44748 jjdelcerro
    }
1182 45326 omartinez
1183
    public void setUpdateValuesLimits(int limit, int featuresLimit) {
1184
        this.updateValuesTimeLimit = limit;
1185
        this.updateValuesFeaturesLimit = featuresLimit;
1186
        doUpdateValuesList();
1187 44855 jjdelcerro
    }
1188
1189 45326 omartinez
    public int getNullBehavior() {
1190
        return (int) ((LabeledValue) this.ddnNullBehavior.getSelectedItem()).getValue();
1191
    }
1192 45331 omartinez
1193 45326 omartinez
    public int setNullBehavior(int nullBehaviorValue) {
1194 45331 omartinez
        int n = 0;
1195 45326 omartinez
        for (LabeledValue nullBehavior : nullBehaviors) {
1196
            int toInt = (int) nullBehavior.getValue();
1197
            if (nullBehaviorValue == toInt) {
1198
                break;
1199
            }
1200
            n++;
1201
        }
1202
        if (this.nullBehaviors.length <= n) {
1203
            return -1;
1204
        }
1205
        this.ddnNullBehavior.setSelectedIndex(n);
1206
        return n;
1207
    }
1208 45331 omartinez
1209
    private ExpressionBuilder.Value addNullBehavior(DALExpressionBuilder builder, ExpressionBuilder.Value filter, ExpressionBuilder.Value nullValue) {
1210
        if (this.getRelationalOperator() != ExpressionBuilder.OPERATOR_IS_NULL && this.getRelationalOperator() != ExpressionBuilder.OPERATOR_IS_NOT_NULL) {
1211
            if (this.getNullBehavior() == NULL_AS_TRUE) {
1212
                ExpressionBuilder.Function null_function = builder.expression().is_null(nullValue);
1213
                filter = builder.expression().or(null_function, filter);
1214
            } else if (this.getNullBehavior() == NULL_AS_FALSE) {
1215
                ExpressionBuilder.Function null_function = builder.expression().not_is_null(nullValue);
1216
                filter = builder.expression().and(null_function, filter);
1217
            }
1218
        }
1219
        return filter;
1220
    }
1221
1222
    private ExpressionBuilder.Value getFilterForOperatorNull(
1223
            FeatureAttributeDescriptor parentDescriptor,
1224
            FeatureAttributeDescriptor descriptor,
1225
            DALExpressionBuilder builder,
1226
            Field field) {
1227
1228
        ExpressionBuilder.Value filter = null;
1229
        if (parentDescriptor == null) {
1230
            filter = builder.expression().is_null(builder.expression().column(this.store.getName(), descriptor.getName()));
1231
        } else {
1232
            // Se busca en campos de una tabla relacionada.
1233
            switch (parentDescriptor.getRelationType()) {
1234
                case DynField.RELATION_TYPE_COLLABORATION:
1235
                case DynField.RELATION_TYPE_IDENTITY:
1236
                    filter = builder.expression().is_null(builder.foreing_value(
1237
                            parentDescriptor.getName(),
1238
                            descriptor.getName()
1239
                    ));
1240 46699 fdiaz
                    break;
1241 45331 omartinez
                case DynField.RELATION_TYPE_AGGREGATE:
1242
                case DynField.RELATION_TYPE_COMPOSITION:
1243
                    ExpressionBuilder.Value op_composition = null;
1244
                    op_composition = builder.expression().is_null(builder.expression().column(
1245
                            field.getFeatureStore().getName(),
1246
                            descriptor.getName()
1247
                    ));
1248 46517 fdiaz
                    filter = buildExists(builder, field, op_composition);
1249 45331 omartinez
            }
1250
        }
1251
1252
        filter = builder.expression().group(filter);
1253
        return filter;
1254
    }
1255
1256
    private ExpressionBuilder.Value getFilterForOperatorNotNull(
1257
            FeatureAttributeDescriptor parentDescriptor,
1258
            FeatureAttributeDescriptor descriptor,
1259
            DALExpressionBuilder builder,
1260
            Field field) {
1261
1262
        ExpressionBuilder.Value filter = null;
1263
        if (parentDescriptor == null) {
1264
            filter = builder.expression().not_is_null(builder.expression().column(this.store.getName(), descriptor.getName()));
1265
        } else {
1266
            // Se busca en campos de una tabla relacionada.
1267
            switch (parentDescriptor.getRelationType()) {
1268
                case DynField.RELATION_TYPE_COLLABORATION:
1269
                case DynField.RELATION_TYPE_IDENTITY:
1270
                    filter = builder.expression().not_is_null(builder.foreing_value(
1271
                            parentDescriptor.getName(),
1272
                            descriptor.getName()
1273
                    ));
1274 46699 fdiaz
                    break;
1275 45331 omartinez
                case DynField.RELATION_TYPE_AGGREGATE:
1276
                case DynField.RELATION_TYPE_COMPOSITION:
1277
                    ExpressionBuilder.Value op_composition = null;
1278
                    op_composition = builder.expression().not_is_null(builder.expression().column(
1279
                            field.getFeatureStore().getName(),
1280
                            descriptor.getName()
1281
                    ));
1282
1283 46517 fdiaz
                    filter = buildExists(builder, field, op_composition);
1284 45331 omartinez
            }
1285
        }
1286
1287
        filter = builder.expression().group(filter);
1288
        return filter;
1289
    }
1290 44351 jjdelcerro
}