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

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