Revision 44855 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

View differences:

SearchConditionFieldController.java
12 12
import java.util.List;
13 13
import java.util.Map;
14 14
import java.util.Objects;
15
import java.util.logging.Level;
16 15
import javax.json.Json;
17 16
import javax.json.JsonArray;
18 17
import javax.json.JsonArrayBuilder;
......
25 24
import javax.swing.JLabel;
26 25
import javax.swing.JOptionPane;
27 26
import javax.swing.SwingUtilities;
28
import static org.apache.commons.lang3.ArrayUtils.toStringArray;
29 27
import org.apache.commons.lang3.StringUtils;
30 28
import org.gvsig.expressionevaluator.ExpressionBuilder;
31 29
import org.gvsig.fmap.dal.DALLocator;
......
72 70
@SuppressWarnings("UseSpecificCatch")
73 71
public class SearchConditionFieldController {
74 72

  
75
    private static final Logger LOGGER = LoggerFactory.getLogger(SearchConditionFieldController.class);
73
  private static final Logger LOGGER = LoggerFactory.getLogger(SearchConditionFieldController.class);
76 74

  
77
    private static class Field extends LabeledValueImpl<String> {
75
  private static class Field extends LabeledValueImpl<String> {
78 76

  
79
        FeatureAttributeDescriptor attrdesc;
80
        private final FeatureStore store;
81
        private final int presentationMode;
82
        private final boolean showStoreName;
83
        private final FeatureAttributeDescriptor[] path;
77
    FeatureAttributeDescriptor attrdesc;
78
    private final FeatureStore store;
79
    private final int presentationMode;
80
    private final boolean showStoreName;
81
    private final FeatureAttributeDescriptor[] path;
84 82

  
85
        public Field(FeatureAttributeDescriptor[] path, FeatureStore store, FeatureAttributeDescriptor attrdesc, int presentationMode) {
86
            this(path, store, attrdesc, presentationMode, false);
87
        }
83
    public Field(FeatureAttributeDescriptor[] path, FeatureStore store, FeatureAttributeDescriptor attrdesc, int presentationMode) {
84
      this(path, store, attrdesc, presentationMode, false);
85
    }
88 86

  
89
        public Field(
90
                FeatureAttributeDescriptor[] path,
91
                FeatureStore store,
92
                FeatureAttributeDescriptor attrdesc,
93
                int presentationMode,
94
                boolean showStoreName
95
        ) {
96
            super(
97
                    getAttributeDescriptorLabel(attrdesc, store.getName()),
98
                    attrdesc.getName()
99
            );
100
            this.path = path;
101
            this.store = store;
102
            this.attrdesc = attrdesc;
103
            this.presentationMode = presentationMode;
104
            this.showStoreName = showStoreName;
105
        }
87
    public Field(
88
            FeatureAttributeDescriptor[] path,
89
            FeatureStore store,
90
            FeatureAttributeDescriptor attrdesc,
91
            int presentationMode,
92
            boolean showStoreName
93
    ) {
94
      super(
95
              getAttributeDescriptorLabel(attrdesc, store.getName()),
96
              attrdesc.getName()
97
      );
98
      this.path = path;
99
      this.store = store;
100
      this.attrdesc = attrdesc;
101
      this.presentationMode = presentationMode;
102
      this.showStoreName = showStoreName;
103
    }
106 104

  
107
        public FeatureAttributeDescriptor[] getPath() {
108
            return this.path;
109
        }
105
    public FeatureAttributeDescriptor[] getPath() {
106
      return this.path;
107
    }
110 108

  
111
        @Override
112
        public String getLabel() {
113
            String theLabel = getAttributeDescriptorLabel(attrdesc, showStoreName ? store.getName() : null);
114
            switch (this.presentationMode) {
115
                case Search.OrderedAttribute.TYPE_REGURAL:
116
                    break;
117
                case Search.OrderedAttribute.TYPE_FAVORITE:
118
                    theLabel = "<html><b>" + theLabel + "</b></html>";
119
                    break;
120
                case Search.OrderedAttribute.TYPE_RECENT:
121
                    theLabel = "<html><i><b>" + theLabel + "</b></i></html>";
122
                    break;
123
            }
124
            return theLabel;
125
        }
109
    @Override
110
    public String getLabel() {
111
      String theLabel = getAttributeDescriptorLabel(attrdesc, showStoreName ? store.getName() : null);
112
      switch (this.presentationMode) {
113
        case Search.OrderedAttribute.TYPE_REGURAL:
114
          break;
115
        case Search.OrderedAttribute.TYPE_FAVORITE:
116
          theLabel = "<html><b>" + theLabel + "</b></html>";
117
          break;
118
        case Search.OrderedAttribute.TYPE_RECENT:
119
          theLabel = "<html><i><b>" + theLabel + "</b></i></html>";
120
          break;
121
      }
122
      return theLabel;
123
    }
126 124

  
127
        public FeatureAttributeDescriptor getParentDescriptor() {
128
            int l = this.path.length;
129
            if (l < 2) {
130
                return null;
131
            }
132
            return this.path[l - 2];
133
        }
125
    public FeatureAttributeDescriptor getParentDescriptor() {
126
      int l = this.path.length;
127
      if (l < 2) {
128
        return null;
129
      }
130
      return this.path[l - 2];
131
    }
134 132

  
135
        public FeatureAttributeDescriptor getDescriptor() {
136
            return this.attrdesc;
137
        }
133
    public FeatureAttributeDescriptor getDescriptor() {
134
      return this.attrdesc;
135
    }
138 136

  
139
        public FeatureStore getFeatureStore() {
140
            return this.store;
141
        }
142

  
137
    public FeatureStore getFeatureStore() {
138
      return this.store;
143 139
    }
144 140

  
145
    private FeatureStore store;
146
    private final JLabel lblFields;
147
    private final JLabel lblExtraFields;
148
    private final JLabel lblLogicalOperators;
149
    private final JLabel lblRelationalOperators;
150
    private final JComboBox cboValue;
151
    private Object valueAssigned = null;
141
  }
152 142

  
153
    private DropDown ddnFields;
154
    private DropDown ddnLogicalOperators;
155
    private DropDown ddnRelationalOperators;
143
  private FeatureStore store;
144
  private final JLabel lblFields;
145
  private final JLabel lblExtraFields;
146
  private final JLabel lblLogicalOperators;
147
  private final JLabel lblRelationalOperators;
148
  private final JComboBox cboValue;
149
  private Object valueAssigned = null;
156 150

  
157
    private LabeledValue[] relationalOperators;
158
    private LabeledValue[] logicalOperators;
159
    private final int SIZE_ORDERED_ATTRIBUTES = 20;
151
  private DropDown ddnFields;
152
  private DropDown ddnLogicalOperators;
153
  private DropDown ddnRelationalOperators;
160 154

  
161
    public SearchConditionFieldController(
162
            FeatureStore store,
163
            JLabel lblFields,
164
            JLabel lblExtraFields,
165
            JLabel lblRelationalOperators,
166
            JComboBox cboValue,
167
            JLabel lblLogicalOperators
168
    ) {
169
        this.store = store;
170
        this.lblFields = lblFields;
171
        this.lblExtraFields = lblExtraFields;
172
        this.lblRelationalOperators = lblRelationalOperators;
173
        this.cboValue = cboValue;
174
        this.lblLogicalOperators = lblLogicalOperators;
175
        this.initComponents();
176
    }
155
  private LabeledValue[] relationalOperators;
156
  private LabeledValue[] logicalOperators;
157
  private final int SIZE_ORDERED_ATTRIBUTES = 20;
177 158

  
178
    public boolean isAValidRelationOperator(String name) {
179
        for (LabeledValue relationalOperator : relationalOperators) {
180
            if (StringUtils.equalsIgnoreCase(name, (CharSequence) relationalOperator.getValue())) {
181
                return true;
182
            }
183
        }
184
        return false;
159
  public SearchConditionFieldController(
160
          FeatureStore store,
161
          JLabel lblFields,
162
          JLabel lblExtraFields,
163
          JLabel lblRelationalOperators,
164
          JComboBox cboValue,
165
          JLabel lblLogicalOperators
166
  ) {
167
    this.store = store;
168
    this.lblFields = lblFields;
169
    this.lblExtraFields = lblExtraFields;
170
    this.lblRelationalOperators = lblRelationalOperators;
171
    this.cboValue = cboValue;
172
    this.lblLogicalOperators = lblLogicalOperators;
173
    this.initComponents();
174
  }
175

  
176
  public boolean isAValidRelationOperator(String name) {
177
    for (LabeledValue relationalOperator : relationalOperators) {
178
      if (StringUtils.equalsIgnoreCase(name, (CharSequence) relationalOperator.getValue())) {
179
        return true;
180
      }
185 181
    }
182
    return false;
183
  }
186 184

  
187
    private void initComponents() {
188
        try {
189
            I18nManager i18n = ToolsLocator.getI18nManager();
190
            ToolsSwingManager toolsSwingManager = ToolsSwingLocator.getToolsSwingManager();
185
  private void initComponents() {
186
    try {
187
      I18nManager i18n = ToolsLocator.getI18nManager();
188
      ToolsSwingManager toolsSwingManager = ToolsSwingLocator.getToolsSwingManager();
191 189

  
192
            relationalOperators = new LabeledValue[]{
193
                new LabeledValueImpl(i18n.getTranslation("_Equals_to"), ExpressionBuilder.OPERATOR_EQ),
194
                new LabeledValueImpl(i18n.getTranslation("_Like_to"), ExpressionBuilder.OPERATOR_ILIKE),
195
                new LabeledValueImpl(i18n.getTranslation("_Not_equals_to"), ExpressionBuilder.OPERATOR_NE),
196
                new LabeledValueImpl(i18n.getTranslation("_Greater_than"), ExpressionBuilder.OPERATOR_GT),
197
                new LabeledValueImpl(i18n.getTranslation("_Greater_or_equal_to"), ExpressionBuilder.OPERATOR_GE),
198
                new LabeledValueImpl(i18n.getTranslation("_Less_than"), ExpressionBuilder.OPERATOR_LT),
199
                new LabeledValueImpl(i18n.getTranslation("_Less_or_equal_to"), ExpressionBuilder.OPERATOR_LE)
200
            };
190
      relationalOperators = new LabeledValue[]{
191
        new LabeledValueImpl(i18n.getTranslation("_Equals_to"), ExpressionBuilder.OPERATOR_EQ),
192
        new LabeledValueImpl(i18n.getTranslation("_Like_to"), ExpressionBuilder.OPERATOR_ILIKE),
193
        new LabeledValueImpl(i18n.getTranslation("_Not_equals_to"), ExpressionBuilder.OPERATOR_NE),
194
        new LabeledValueImpl(i18n.getTranslation("_Greater_than"), ExpressionBuilder.OPERATOR_GT),
195
        new LabeledValueImpl(i18n.getTranslation("_Greater_or_equal_to"), ExpressionBuilder.OPERATOR_GE),
196
        new LabeledValueImpl(i18n.getTranslation("_Less_than"), ExpressionBuilder.OPERATOR_LT),
197
        new LabeledValueImpl(i18n.getTranslation("_Less_or_equal_to"), ExpressionBuilder.OPERATOR_LE)
198
      };
201 199

  
202
            logicalOperators = new LabeledValue[]{
203
                new LabeledValueImpl(i18n.getTranslation("_Or"), ExpressionBuilder.OPERATOR_OR),
204
                new LabeledValueImpl(i18n.getTranslation("_And"), ExpressionBuilder.OPERATOR_AND)
205
            };
200
      logicalOperators = new LabeledValue[]{
201
        new LabeledValueImpl(i18n.getTranslation("_Or"), ExpressionBuilder.OPERATOR_OR),
202
        new LabeledValueImpl(i18n.getTranslation("_And"), ExpressionBuilder.OPERATOR_AND)
203
      };
206 204

  
207
            this.lblExtraFields.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
205
      this.lblExtraFields.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
208 206

  
209
            this.ddnFields = toolsSwingManager.createDropDown(lblFields);
210
            this.ddnFields.setVisibleDropdownArrow(false);
211
            this.ddnRelationalOperators = toolsSwingManager.createDropDown(lblRelationalOperators);
212
            this.ddnRelationalOperators.setVisibleDropdownArrow(false);
213
            if (lblLogicalOperators != null) {
214
                this.ddnLogicalOperators = toolsSwingManager.createDropDown(lblLogicalOperators);
215
                this.ddnLogicalOperators.setVisibleDropdownArrow(false);
216
            }
207
      this.ddnFields = toolsSwingManager.createDropDown(lblFields);
208
      this.ddnFields.setVisibleDropdownArrow(false);
209
      this.ddnRelationalOperators = toolsSwingManager.createDropDown(lblRelationalOperators);
210
      this.ddnRelationalOperators.setVisibleDropdownArrow(false);
211
      if (lblLogicalOperators != null) {
212
        this.ddnLogicalOperators = toolsSwingManager.createDropDown(lblLogicalOperators);
213
        this.ddnLogicalOperators.setVisibleDropdownArrow(false);
214
      }
217 215

  
218
            DefaultComboBoxModel modelRelationalOperators = new DefaultComboBoxModel();
219
            for (LabeledValue op : relationalOperators) {
220
                modelRelationalOperators.addElement(op);
221
            }
222
            this.ddnRelationalOperators.setModel(modelRelationalOperators);
216
      DefaultComboBoxModel modelRelationalOperators = new DefaultComboBoxModel();
217
      for (LabeledValue op : relationalOperators) {
218
        modelRelationalOperators.addElement(op);
219
      }
220
      this.ddnRelationalOperators.setModel(modelRelationalOperators);
223 221

  
224
            if (this.ddnLogicalOperators != null) {
225
                DefaultComboBoxModel modelLogicalOperators = new DefaultComboBoxModel();
226
                for (LabeledValue op : logicalOperators) {
227
                    modelLogicalOperators.addElement(op);
228
                }
229
                this.ddnLogicalOperators.setModel(modelLogicalOperators);
230
            }
231
            FeatureType featureType = store.getDefaultFeatureType();
232
            Search search = (Search) ToolsLocator.getComplementsManager().get(
233
                    Search.COMPLEMENT_MANE, featureType
234
            );
235
            List<Search.OrderedAttribute> orderedAttributes = search.getOrderedAttributes(
236
                    Search.BASIC_TYPES_FILTER,
237
                    Search.STR_INT_LONG_LABEL_ORDER,
238
                    SIZE_ORDERED_ATTRIBUTES
239
            );
240
            List<ImageIcon> icons = new ArrayList<>();
222
      if (this.ddnLogicalOperators != null) {
223
        DefaultComboBoxModel modelLogicalOperators = new DefaultComboBoxModel();
224
        for (LabeledValue op : logicalOperators) {
225
          modelLogicalOperators.addElement(op);
226
        }
227
        this.ddnLogicalOperators.setModel(modelLogicalOperators);
228
      }
229
      FeatureType featureType = store.getDefaultFeatureType();
230
      Search search = (Search) ToolsLocator.getComplementsManager().get(
231
              Search.COMPLEMENT_MANE, featureType
232
      );
233
      List<Search.OrderedAttribute> orderedAttributes = search.getOrderedAttributes(
234
              Search.BASIC_TYPES_FILTER,
235
              Search.STR_INT_LONG_LABEL_ORDER,
236
              SIZE_ORDERED_ATTRIBUTES
237
      );
238
      List<ImageIcon> icons = new ArrayList<>();
241 239
//            DataTypesManager dataTypeManager = ToolsLocator.getDataTypesManager();
242
            IconTheme iconTheme = ToolsSwingLocator.getIconThemeManager().getCurrent();
243
            DefaultComboBoxModel model = new DefaultComboBoxModel();
244
            for (Search.OrderedAttribute attr : orderedAttributes) {
245
                FeatureAttributeDescriptor attrdesc = attr.getDescriptor();
246
                Field field = new Field(
247
                        new FeatureAttributeDescriptor[]{attrdesc},
248
                        this.store,
249
                        attrdesc,
250
                        attr.getType()
251
                );
252
                model.addElement(field);
253
                String iconName = attrdesc.getDataType().getIconName();
254
                if (iconTheme.exists(iconName)) {
255
                    icons.add(iconTheme.get(iconName));
256
                } else {
257
                    icons.add(null);
258
                }
259
            }
260
            this.ddnFields.setIcons(icons);
261
            this.ddnFields.setModel(model);
262
            this.ddnFields.addItemListener(new ItemListener() {
263
                @Override
264
                public void itemStateChanged(ItemEvent e) {
265
                    if (e.getStateChange() == ItemEvent.SELECTED) {
266
                        doUpdateValuesList();
267
                    }
240
      IconTheme iconTheme = ToolsSwingLocator.getIconThemeManager().getCurrent();
241
      DefaultComboBoxModel model = new DefaultComboBoxModel();
242
      for (Search.OrderedAttribute attr : orderedAttributes) {
243
        FeatureAttributeDescriptor attrdesc = attr.getDescriptor();
244
        Field field = new Field(
245
                new FeatureAttributeDescriptor[]{attrdesc},
246
                this.store,
247
                attrdesc,
248
                attr.getType()
249
        );
250
        model.addElement(field);
251
        String iconName = attrdesc.getDataType().getIconName();
252
        if (iconTheme.exists(iconName)) {
253
          icons.add(iconTheme.get(iconName));
254
        } else {
255
          icons.add(null);
256
        }
257
      }
258
      this.ddnFields.setIcons(icons);
259
      this.ddnFields.setModel(model);
260
      this.ddnFields.addItemListener(new ItemListener() {
261
        @Override
262
        public void itemStateChanged(ItemEvent e) {
263
          if (e.getStateChange() == ItemEvent.SELECTED) {
264
            doUpdateValuesList();
265
          }
268 266

  
269
                }
270
            });
267
        }
268
      });
271 269

  
272
            this.lblExtraFields.addMouseListener(new MouseAdapter() {
273
                @Override
274
                public void mouseClicked(MouseEvent e) {
275
                    doSelectMoreFields();
276
                }
277
            });
278
            clear();
279
        } catch (Exception ex) {
280
            throw new RuntimeException(ex);
270
      this.lblExtraFields.addMouseListener(new MouseAdapter() {
271
        @Override
272
        public void mouseClicked(MouseEvent e) {
273
          doSelectMoreFields();
281 274
        }
275
      });
276
      clear();
277
    } catch (Exception ex) {
278
      throw new RuntimeException(ex);
282 279
    }
280
  }
283 281

  
284
    private FeatureType getFeatureType() {
285
        try {
286
            return this.store.getDefaultFeatureType();
287
        } catch (DataException ex) {
288
            return null;
289
        }
282
  private FeatureType getFeatureType() {
283
    try {
284
      return this.store.getDefaultFeatureType();
285
    } catch (DataException ex) {
286
      return null;
290 287
    }
288
  }
291 289

  
292
    private void doSelectMoreFields() {
293
        DefaultFeatureAttributeSelectionPanel panel = new DefaultFeatureAttributeSelectionPanel(store);
294
        WindowManager_v2 winManager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
295
        final Dialog dialog = winManager.createDialog(
296
                panel,
297
                "Select attribute",
298
                null,
299
                WindowManager_v2.BUTTONS_OK_CANCEL
290
  private void doSelectMoreFields() {
291
    DefaultFeatureAttributeSelectionPanel panel = new DefaultFeatureAttributeSelectionPanel(store);
292
    WindowManager_v2 winManager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
293
    final Dialog dialog = winManager.createDialog(
294
            panel,
295
            "Select attribute",
296
            null,
297
            WindowManager_v2.BUTTONS_OK_CANCEL
298
    );
299
    dialog.addActionListener((ActionEvent e) -> {
300
      if (dialog.getAction() == WindowManager_v2.BUTTONS_OK) {
301
        doAddAndSelect(
302
                panel.getSelectedStore(),
303
                panel.getSelectedAttributeDescriptor(),
304
                panel.getSelectedPath()
300 305
        );
301
        dialog.addActionListener((ActionEvent e) -> {
302
            if (dialog.getAction() == WindowManager_v2.BUTTONS_OK) {
303
                doAddAndSelect(
304
                        panel.getSelectedStore(),
305
                        panel.getSelectedAttributeDescriptor(),
306
                        panel.getSelectedPath()
307
                );
308
            }
309
        });
310
        dialog.show(WindowManager.MODE.DIALOG);
306
      }
307
    });
308
    dialog.show(WindowManager.MODE.DIALOG);
311 309

  
312
    }
310
  }
313 311

  
314
    private void doAddAndSelect(FeatureStore theStore, FeatureAttributeDescriptor attrdesc, FeatureAttributeDescriptor[] path) {
315
        DefaultComboBoxModel<Field> model = (DefaultComboBoxModel) this.ddnFields.getModel();
316
        for (int i = 0; i < model.getSize(); i++) {
317
            Field field = model.getElementAt(i);
318
            FeatureAttributeDescriptor attrdescN = field.getDescriptor();
319
            if (isTheSameStore(theStore, attrdescN.getStore())
320
                    && StringUtils.equalsIgnoreCase(attrdesc.getName(), attrdescN.getName())) {
321
                this.setAttribute(i);
322
                return;
323
            }
312
  private void doAddAndSelect(FeatureStore theStore, FeatureAttributeDescriptor attrdesc, FeatureAttributeDescriptor[] path) {
313
    DefaultComboBoxModel<Field> model = (DefaultComboBoxModel) this.ddnFields.getModel();
314
    for (int i = 0; i < model.getSize(); i++) {
315
      Field field = model.getElementAt(i);
316
      FeatureAttributeDescriptor attrdescN = field.getDescriptor();
317
      if (isTheSameStore(theStore, attrdescN.getStore())
318
              && StringUtils.equalsIgnoreCase(attrdesc.getName(), attrdescN.getName())) {
319
        this.setAttribute(i);
320
        return;
321
      }
322
    }
323
    Field field = new Field(
324
            path,
325
            theStore,
326
            attrdesc,
327
            Search.OrderedAttribute.TYPE_REGURAL,
328
            !isTheSameStore(store, theStore)
329
    );
330
    ThreadSafeDialogsManager dialogManager = ToolsSwingLocator.getThreadSafeDialogsManager();
331
    if (field.getPath().length > 2) {
332
      dialogManager.messageDialog(
333
              "It not supported to search through this field." + "\n"
334
              + "Too many links.",
335
              "_Warning",
336
              JOptionPane.WARNING_MESSAGE
337
      );
338
      return;
339
    }
340
    FeatureAttributeDescriptor parentDescriptor = field.getParentDescriptor();
341
    switch (parentDescriptor.getRelationType()) {
342
      case DynField.RELATION_TYPE_AGGREGATE:
343
      case DynField.RELATION_TYPE_COMPOSITION:
344
        if (getForeingKeyName(field.getFeatureStore(), this.store) == null) {
345
          dialogManager.messageDialog(
346
                  "It not supported to search through this field." + "\n"
347
                  + "The link field was not found.",
348
                  "_Warning",
349
                  JOptionPane.WARNING_MESSAGE
350
          );
351
          return;
324 352
        }
325
        Field field = new Field(
326
                path,
327
                theStore,
328
                attrdesc,
329
                Search.OrderedAttribute.TYPE_REGURAL,
330
                !isTheSameStore(store, theStore)
331
        );
332
        ThreadSafeDialogsManager dialogManager = ToolsSwingLocator.getThreadSafeDialogsManager();
333
        if (field.getPath().length > 2) {
334
            dialogManager.messageDialog(
335
                    "It not supported to search through this field." + "\n"
336
                    + "Too many links.",
337
                    "_Warning",
338
                    JOptionPane.WARNING_MESSAGE
339
            );
340
            return;
353
        if (getPrimaryKeyName(this.store) == null) {
354
          dialogManager.messageDialog(
355
                  "It not supported to search through this field." + "\n"
356
                  + "A simple primary key was not found.",
357
                  "_Warning",
358
                  JOptionPane.WARNING_MESSAGE
359
          );
360
          return;
341 361
        }
342
        FeatureAttributeDescriptor parentDescriptor = field.getParentDescriptor();
343
        switch (parentDescriptor.getRelationType()) {
344
            case DynField.RELATION_TYPE_AGGREGATE:
345
            case DynField.RELATION_TYPE_COMPOSITION:
346
                if (getForeingKeyName(field.getFeatureStore(), this.store) == null) {
347
                    dialogManager.messageDialog(
348
                            "It not supported to search through this field." + "\n"
349
                            + "The link field was not found.",
350
                            "_Warning",
351
                            JOptionPane.WARNING_MESSAGE
352
                    );
353
                    return;
354
                }
355
                if (getPrimaryKeyName(this.store) == null) {
356
                    dialogManager.messageDialog(
357
                            "It not supported to search through this field." + "\n"
358
                            + "A simple primary key was not found.",
359
                            "_Warning",
360
                            JOptionPane.WARNING_MESSAGE
361
                    );
362
                    return;
363
                }
364
        }
365
        model.addElement(field);
366
        IconTheme iconTheme = ToolsSwingLocator.getIconThemeManager().getCurrent();
367
        this.ddnFields.getIcons().add(iconTheme.get(attrdesc.getDataType().getIconName()));
368
        this.setAttribute(model.getSize() - 1);
369 362
    }
363
    model.addElement(field);
364
    IconTheme iconTheme = ToolsSwingLocator.getIconThemeManager().getCurrent();
365
    this.ddnFields.getIcons().add(iconTheme.get(attrdesc.getDataType().getIconName()));
366
    this.setAttribute(model.getSize() - 1);
367
  }
370 368

  
371
    public void clear() {
372
        this.ddnRelationalOperators.setSelectedIndex(0);
373
        if (this.ddnLogicalOperators != null) {
374
            this.ddnLogicalOperators.setSelectedIndex(1);
375
        }
376
        this.cboValue.setSelectedIndex(-1);
369
  public void clear() {
370
    this.ddnRelationalOperators.setSelectedIndex(0);
371
    if (this.ddnLogicalOperators != null) {
372
      this.ddnLogicalOperators.setSelectedIndex(1);
377 373
    }
374
    this.cboValue.setSelectedIndex(-1);
375
  }
378 376

  
379
    private void doUpdateValuesList() {
380
        final Field field = (Field) this.ddnFields.getSelectedItem();
381
        if (field == null) {
382
            return;
383
        }
377
  private void doUpdateValuesList() {
378
    final Field field = (Field) this.ddnFields.getSelectedItem();
379
    if (field == null) {
380
      return;
381
    }
384 382

  
385
        final List<Object> values = new ArrayList<>();
386
        final int limit = 60;
387
        final long timeLimit = System.currentTimeMillis() + limit * 1000;
388
        final DefaultComboBoxModel model = new DefaultComboBoxModel();
389
        this.setEnabled(false);
390
        final FeatureStore theStore = field.getFeatureStore();
391
        final FeatureQuery query = theStore.createFeatureQuery();
392
        query.addAttributeName(field.getDescriptor().getName());
393
        query.setLimit(1000);
394
        Thread th = new Thread(new Runnable() {
383
    final List<Object> values = new ArrayList<>();
384
    final int limit = 60;
385
    final long timeLimit = System.currentTimeMillis() + limit * 1000;
386
    final DefaultComboBoxModel model = new DefaultComboBoxModel();
387
    this.setEnabled(false);
388
    final FeatureStore theStore = field.getFeatureStore();
389
    final FeatureQuery query = theStore.createFeatureQuery();
390
    query.addAttributeName(field.getDescriptor().getName());
391
    query.setLimit(1000);
392
    Thread th = new Thread(new Runnable() {
393
      @Override
394
      public void run() {
395
        try {
396
          FeatureSet set = theStore.getFeatureSet(query);
397
          set.accept(new Visitor() {
395 398
            @Override
396
            public void run() {
397
                try {
398
                    FeatureSet set = theStore.getFeatureSet(query);
399
                    set.accept(new Visitor() {
400
                        @Override
401
                        public void visit(Object o) throws VisitCanceledException, BaseException {
402
                            Object value = ((Feature) o).get(field.getDescriptor().getName());
403
                            if (!values.contains(value)) {
404
                                values.add(value);
405
                            }
406
                            if (System.currentTimeMillis() > timeLimit) {
407
                                throw new VisitCanceledException();
408
                            }
409
                            if (values.size() > 1000) {
410
                                throw new VisitCanceledException();
411
                            }
412
                        }
413
                    });
414
                } catch (VisitCanceledException ex) {
399
            public void visit(Object o) throws VisitCanceledException, BaseException {
400
              Object value = ((Feature) o).get(field.getDescriptor().getName());
401
              if (!values.contains(value)) {
402
                values.add(value);
403
              }
404
              if (System.currentTimeMillis() > timeLimit) {
405
                throw new VisitCanceledException();
406
              }
407
              if (values.size() > 1000) {
408
                throw new VisitCanceledException();
409
              }
410
            }
411
          });
412
        } catch (VisitCanceledException ex) {
415 413

  
416
                } catch (Exception ex) {
417
                    LOGGER.warn("Can't update list of values of '" + field.getLabel() + "'.", ex);
418
                }
419
                List<LabeledValue> elements = new ArrayList<>();
420
                if (!values.isEmpty()) {
421
                    LabeledValue[] availableValues = field.getDescriptor().getAvailableValues();
422
                    Map<String, String> availableValuesMap = new HashMap<>();
423
                    if (availableValues != null) {
424
                        for (LabeledValue availableValue : availableValues) {
425
                            availableValuesMap.put(
426
                                    Objects.toString(availableValue.getValue()),
427
                                    availableValue.getLabel()
428
                            );
429
                        }
430
                    }
431
                    elements.add(new LabeledValueImpl("", null));
432
                    for (Object value : values) {
433
                        String key = Objects.toString(value);
434
                        String label = availableValuesMap.getOrDefault(key, key);
435
                        elements.add(new LabeledValueImpl(label, value));
436
                    }
437
                    elements.sort(null);
414
        } catch (Exception ex) {
415
          LOGGER.warn("Can't update list of values of '" + field.getLabel() + "'.", ex);
416
        }
417
        List<LabeledValue> elements = new ArrayList<>();
418
        if (!values.isEmpty()) {
419
          LabeledValue[] availableValues = field.getDescriptor().getAvailableValues();
420
          Map<String, String> availableValuesMap = new HashMap<>();
421
          if (availableValues != null) {
422
            for (LabeledValue availableValue : availableValues) {
423
              availableValuesMap.put(
424
                      Objects.toString(availableValue.getValue()),
425
                      availableValue.getLabel()
426
              );
427
            }
428
          }
429
          elements.add(new LabeledValueImpl("", null));
430
          for (Object value : values) {
431
            String key = Objects.toString(value);
432
            String label = availableValuesMap.getOrDefault(key, key);
433
            elements.add(new LabeledValueImpl(label, value));
434
          }
435
          elements.sort(null);
438 436

  
439
                }
440
                for (LabeledValue element : elements) {
441
                    model.addElement(element);
442
                }
443
                SwingUtilities.invokeLater(new Runnable() {
444
                    @Override
445
                    public void run() {
446
                        cboValue.setModel(model);
447
                        if (valueAssigned != null) {
448
                            cboValue.setSelectedItem(valueAssigned);
449
                            valueAssigned = null;
450
                        }
451
                        setEnabled(true);
452
                    }
453
                });
437
        }
438
        for (LabeledValue element : elements) {
439
          model.addElement(element);
440
        }
441
        SwingUtilities.invokeLater(new Runnable() {
442
          @Override
443
          public void run() {
444
            cboValue.setModel(model);
445
            if (valueAssigned != null) {
446
              cboValue.setSelectedItem(valueAssigned);
447
              valueAssigned = null;
454 448
            }
449
            setEnabled(true);
450
          }
455 451
        });
456
        th.start();
457
    }
452
      }
453
    });
454
    th.start();
455
  }
458 456

  
459
    public void setEnabled(boolean enabled) {
460
        this.ddnFields.setEnabled(enabled);
461
        if (this.ddnLogicalOperators != null) {
462
            this.ddnLogicalOperators.setEnabled(enabled);
463
        }
464
        this.ddnRelationalOperators.setEnabled(enabled);
465
        this.lblExtraFields.setEnabled(enabled);
457
  public void setEnabled(boolean enabled) {
458
    this.ddnFields.setEnabled(enabled);
459
    if (this.ddnLogicalOperators != null) {
460
      this.ddnLogicalOperators.setEnabled(enabled);
466 461
    }
462
    this.ddnRelationalOperators.setEnabled(enabled);
463
    this.lblExtraFields.setEnabled(enabled);
464
  }
467 465

  
468
    public String getRelationalOperator() {
469
        LabeledValue<String> op = (LabeledValue) this.ddnRelationalOperators.getSelectedItem();
470
        if (op == null) {
471
            return null;
472
        }
473
        return op.getValue();
466
  public String getRelationalOperator() {
467
    LabeledValue<String> op = (LabeledValue) this.ddnRelationalOperators.getSelectedItem();
468
    if (op == null) {
469
      return null;
474 470
    }
471
    return op.getValue();
472
  }
475 473

  
476
    public int setRelationalOperator(String name) {
477
        int n = 0;
478
        for (LabeledValue relationalOperator : relationalOperators) {
479
            if (StringUtils.equalsIgnoreCase(name, (CharSequence) relationalOperator.getValue())) {
480
                break;
481
            }
482
            n++;
483
        }
484
        if (this.relationalOperators.length <= n) {
485
            return -1;
486
        }
487
        this.ddnRelationalOperators.setSelectedIndex(n);
488
        return n;
474
  public int setRelationalOperator(String name) {
475
    int n = 0;
476
    for (LabeledValue relationalOperator : relationalOperators) {
477
      if (StringUtils.equalsIgnoreCase(name, (CharSequence) relationalOperator.getValue())) {
478
        break;
479
      }
480
      n++;
489 481
    }
482
    if (this.relationalOperators.length <= n) {
483
      return -1;
484
    }
485
    this.ddnRelationalOperators.setSelectedIndex(n);
486
    return n;
487
  }
490 488

  
491
    public String getLogicalOperator() {
492
        if (this.ddnLogicalOperators == null) {
493
            return null;
494
        }
495
        LabeledValue<String> rel = (LabeledValue) this.ddnLogicalOperators.getSelectedItem();
496
        if (rel == null) {
497
            return null;
498
        }
499
        return rel.getValue();
489
  public String getLogicalOperator() {
490
    if (this.ddnLogicalOperators == null) {
491
      return null;
500 492
    }
493
    LabeledValue<String> rel = (LabeledValue) this.ddnLogicalOperators.getSelectedItem();
494
    if (rel == null) {
495
      return null;
496
    }
497
    return rel.getValue();
498
  }
501 499

  
502
    public void setLogicalOperator(String operator) {
503
        if (this.ddnLogicalOperators == null) {
504
            return;
505
        }
506
        ComboBoxModel model = this.ddnLogicalOperators.getModel();
507
        for (int i = 0; i < model.getSize(); i++) {
508
            LabeledValue modelValue = (LabeledValue) model.getElementAt(i);
509
            String value = (String) modelValue.getValue();
510
            if (StringUtils.equals(value, operator)) {
511
                this.ddnLogicalOperators.setSelectedIndex(i);
512
                break;
513
            }
514
        }
500
  public void setLogicalOperator(String operator) {
501
    if (this.ddnLogicalOperators == null) {
502
      return;
515 503
    }
504
    ComboBoxModel model = this.ddnLogicalOperators.getModel();
505
    for (int i = 0; i < model.getSize(); i++) {
506
      LabeledValue modelValue = (LabeledValue) model.getElementAt(i);
507
      String value = (String) modelValue.getValue();
508
      if (StringUtils.equals(value, operator)) {
509
        this.ddnLogicalOperators.setSelectedIndex(i);
510
        break;
511
      }
512
    }
513
  }
516 514

  
517
    public Object getValue() {
518
        final Field field = (Field) this.ddnFields.getSelectedItem();
519
        if (field == null) {
520
            return null;
521
        }
522
        Object v = this.cboValue.getSelectedItem();
523
        if (v == null) {
524
            return null;
525
        }
526
        if (v instanceof LabeledValue) {
527
            v = ((LabeledValue) v).getValue();
528
            if (v == null) {
529
                return null;
530
            }
531
        }
532
        if (v instanceof CharSequence) {
533
            if (StringUtils.isBlank((CharSequence) v)) {
534
                return null;
535
            }
536
        }
537
        Coercion coercion = field.getDescriptor().getDataType().getCoercion();
538
        try {
539
            return coercion.coerce(v);
540
        } catch (CoercionException ex) {
541
            return null;
542
        }
515
  public Object getValue() {
516
    final Field field = (Field) this.ddnFields.getSelectedItem();
517
    if (field == null) {
518
      return null;
543 519
    }
520
    Object v = this.cboValue.getSelectedItem();
521
    if (v == null) {
522
      return null;
523
    }
524
    if (v instanceof LabeledValue) {
525
      v = ((LabeledValue) v).getValue();
526
      if (v == null) {
527
        return null;
528
      }
529
    }
530
    if (v instanceof CharSequence) {
531
      if (StringUtils.isBlank((CharSequence) v)) {
532
        return null;
533
      }
534
    }
535
    Coercion coercion = field.getDescriptor().getDataType().getCoercion();
536
    try {
537
      return coercion.coerce(v);
538
    } catch (CoercionException ex) {
539
      return null;
540
    }
541
  }
544 542

  
545
    public void setValue(Object value) {
546
        this.cboValue.setSelectedItem(value);
547
        this.valueAssigned = value;
543
  public void setValue(Object value) {
544
    this.cboValue.setSelectedItem(value);
545
    this.valueAssigned = value;
546
  }
547

  
548
  private Field getCurrentField() {
549
    final Field field = (Field) this.ddnFields.getSelectedItem();
550
    return field;
551
  }
552

  
553
  public int setAttribute(String name) {
554
    ComboBoxModel<Field> model = this.ddnFields.getModel();
555
    for (int i = 0; i < model.getSize(); i++) {
556
      Field x = model.getElementAt(i);
557
      if (StringUtils.equalsIgnoreCase(name, x.getValue())) {
558
        this.setAttribute(i);
559
        return i;
560
      }
548 561
    }
562
    this.setAttribute(-1);
563
    return -1;
564
  }
549 565

  
550
    private Field getCurrentField() {
551
        final Field field = (Field) this.ddnFields.getSelectedItem();
552
        return field;
566
  public void setAttribute(int index) {
567
    try {
568
      this.ddnFields.setSelectedIndex(index);
569
    } catch (Exception ex) {
570
      this.ddnFields.setSelectedIndex(-1);
553 571
    }
572
    doUpdateValuesList();
573
  }
554 574

  
555
    public int setAttribute(String name) {
575
  public int setAttributePath(String[][] pathNames) {
576
    // [[attributeName, storeName],...]
577
    try {
578
      if (pathNames.length == 1) {
579
        String[] path = pathNames[pathNames.length - 1];
580
        String name = path[0];
581
        int index = this.setAttribute(name);
582
        if (index == -1) {
583
          try {
584
            FeatureAttributeDescriptor attrDescriptor = store.getDefaultFeatureType().getAttributeDescriptor(name);
585
            FeatureAttributeDescriptor[] attributePath = new FeatureAttributeDescriptor[]{attrDescriptor};
586
            doAddAndSelect(store, store.getDefaultFeatureType().getAttributeDescriptor(name), attributePath);
587
          } catch (Exception ex) {
588
            LOGGER.warn("Not able to set single path into controller", ex);
589
            return -1;
590
          }
591
        }
592
        return index;
593
      } else {
556 594
        ComboBoxModel<Field> model = this.ddnFields.getModel();
595
        String[] singleArrayPathNameDescriptors = new String[pathNames.length];
596
        for (int i = 0; i < pathNames.length; i++) {
597
          singleArrayPathNameDescriptors[i] = pathNames[i][0];
598
        }
599
        // check the drop
557 600
        for (int i = 0; i < model.getSize(); i++) {
558
            Field x = model.getElementAt(i);
559
            if (StringUtils.equalsIgnoreCase(name, x.getValue())) {
560
                this.setAttribute(i);
561
                return i;
562
            }
601
          Field x = model.getElementAt(i);
602
          String[] arrayDescriptors = new String[x.getPath().length];
603
          FeatureAttributeDescriptor[] path = x.getPath();
604
          for (int j = 0; j < path.length; j++) {
605
            arrayDescriptors[j] = path[j].getName();
606
          }
607
          if (Arrays.equals(singleArrayPathNameDescriptors, arrayDescriptors)) {
608
            this.setAttribute(i);
609
            return i;
610
          }
563 611
        }
564
        this.setAttribute(-1);
565
        return -1;
566
    }
612
        // if not, addit to the drop
613
        DataManager dataManager = DALLocator.getDataManager();
614
        String tableName = pathNames[pathNames.length - 1][1]; // del ultimo path, coger el nombre tabla
615
        FeatureStore theStore = (FeatureStore) dataManager.getStoresRepository().getStore(tableName);
616
        String attributeName = pathNames[pathNames.length - 1][0]; // del ultimo path, coger el nombre attribute
617
        if (theStore != null) {
618
          FeatureAttributeDescriptor attr;
619
          try {
620
            attr = theStore.getDefaultFeatureType().getAttributeDescriptor(attributeName);
621
            FeatureAttributeDescriptor[] attributePath = new FeatureAttributeDescriptor[2];
622
            String firstAttrName = pathNames[0][0];
623
            FeatureAttributeDescriptor firstAttr = store.getDefaultFeatureType().getAttributeDescriptor(firstAttrName);
624
            attributePath[0] = firstAttr;
567 625

  
568
    public void setAttribute(int index) {
569
        try {
570
            this.ddnFields.setSelectedIndex(index);
571
        } catch (Exception ex) {
572
            this.ddnFields.setSelectedIndex(-1);
626
            attributePath[1] = attr;
627
            doAddAndSelect(theStore, attr, attributePath);
628
            return SIZE_ORDERED_ATTRIBUTES - 1;
629
          } catch (Exception ex) {
630
            LOGGER.warn("Not able to set foreign path into controller", ex);
631
          }
632

  
573 633
        }
574
        doUpdateValuesList();
634

  
635
      }
636
    } catch (Exception ex) {
637
      LOGGER.warn("Controller not set.", ex);
575 638
    }
639
    this.setAttribute(-1);
640
    return -1;
641
  }
576 642

  
577
    public int setAttributePath(String[][] pathNames) {
578
        // [[attributeName, storeName],...]
579
        try {
580
            if (pathNames.length == 1) {
581
                String[] path = pathNames[pathNames.length - 1];
582
                String name = path[0];
583
                int index = this.setAttribute(name);
584
                if (index == -1) {
585
                    try {
586
                        FeatureAttributeDescriptor attrDescriptor = store.getDefaultFeatureType().getAttributeDescriptor(name);
587
                        FeatureAttributeDescriptor[] attributePath = new FeatureAttributeDescriptor[]{attrDescriptor};
588
                        doAddAndSelect(store, store.getDefaultFeatureType().getAttributeDescriptor(name), attributePath);
589
                    } catch (Exception ex) {
590
                        LOGGER.warn("Not able to set single path into controller", ex);
591
                        return -1;
592
                    }
593
                }
594
                return index;
595
            } else {
596
                ComboBoxModel<Field> model = this.ddnFields.getModel();
597
                String[] singleArrayPathNameDescriptors = new String[pathNames.length];
598
                for (int i = 0; i < pathNames.length; i++) {
599
                    singleArrayPathNameDescriptors[i] = pathNames[i][0];
600
                }
601
                // check the drop
602
                for (int i = 0; i < model.getSize(); i++) {
603
                    Field x = model.getElementAt(i);
604
                    String[] arrayDescriptors = new String[x.getPath().length];
605
                    FeatureAttributeDescriptor[] path = x.getPath();
606
                    for (int j = 0; j < path.length; j++) {
607
                        arrayDescriptors[j] = path[j].getName();
608
                    }
609
                    if (Arrays.equals(singleArrayPathNameDescriptors, arrayDescriptors)) {
610
                        this.setAttribute(i);
611
                        return i;
612
                    }
613
                }
614
                // if not, addit to the drop
615
                DataManager dataManager = DALLocator.getDataManager();
616
                String tableName = pathNames[pathNames.length - 1][1]; // del ultimo path, coger el nombre tabla
617
                FeatureStore theStore = (FeatureStore) dataManager.getStoresRepository().getStore(tableName);
618
                String attributeName = pathNames[pathNames.length - 1][0]; // del ultimo path, coger el nombre attribute
619
                if (theStore != null) {
620
                    FeatureAttributeDescriptor attr;
621
                    try {
622
                        attr = theStore.getDefaultFeatureType().getAttributeDescriptor(attributeName);
623
                        FeatureAttributeDescriptor[] attributePath = new FeatureAttributeDescriptor[2];
624
                        String firstAttrName = pathNames[0][0];
625
                        FeatureAttributeDescriptor firstAttr = store.getDefaultFeatureType().getAttributeDescriptor(firstAttrName);
626
                        attributePath[0] = firstAttr;
643
  private boolean isTheSameStore(DataStore store1, DataStore store2) {
644
    String store1FullName = store1.getFullName();
645
    String store2FullName = store2.getFullName();
646
    return StringUtils.equalsIgnoreCase(store1FullName, store2FullName);
647
  }
627 648

  
628
                        attributePath[1] = attr;
629
                        doAddAndSelect(theStore, attr, attributePath);
630
                        return SIZE_ORDERED_ATTRIBUTES - 1;
631
                    } catch (Exception ex) {
632
                        LOGGER.warn("Not able to set foreign path into controller", ex);
633
                    }
649
  private String getPrimaryKeyName(FeatureStore store) {
650
    try {
651
      FeatureAttributeDescriptor[] pk = store.getDefaultFeatureType().getPrimaryKey();
652
      if (pk == null || pk.length != 1) {
653
        return null;
654
      }
655
      return pk[0].getName();
656
    } catch (DataException ex) {
657
      return null;
658
    }
659
  }
634 660

  
635
                }
636

  
637
            }
638
        } catch (Exception ex) {
639
            LOGGER.warn("Controller not set.", ex);
661
  private String getForeingKeyName(FeatureStore store, FeatureStore foreingStore) {
662
    try {
663
      for (FeatureAttributeDescriptor descriptor : store.getDefaultFeatureType()) {
664
        if (descriptor.isForeingKey()) {
665
          ForeingKey foreingKey = descriptor.getForeingKey();
666
          if (isTheSameStore(foreingStore, foreingKey.getFeatureStore(null))) {
667
            return descriptor.getName();
668
          }
640 669
        }
641
        this.setAttribute(-1);
642
        return -1;
670
      }
671
    } catch (DataException ex) {
672
      return null;
643 673
    }
674
    return null;
675
  }
644 676

  
645
    private boolean isTheSameStore(DataStore store1, DataStore store2) {
646
        String store1FullName = store1.getFullName();
647
        String store2FullName = store2.getFullName();
648
        return StringUtils.equalsIgnoreCase(store1FullName, store2FullName);
677
  public boolean isValid(StringBuilder message) {
678
    Object value = this.getValue();
679
    if (value == null) {
680
      return true;
649 681
    }
650

  
651
    private String getPrimaryKeyName(FeatureStore store) {
652
        try {
653
            FeatureAttributeDescriptor[] pk = store.getDefaultFeatureType().getPrimaryKey();
654
            if (pk == null || pk.length != 1) {
655
                return null;
656
            }
657
            return pk[0].getName();
658
        } catch (DataException ex) {
659
            return null;
660
        }
682
    Field field = this.getCurrentField();
683
    if (field == null) {
684
      return true;
661 685
    }
662

  
663
    private String getForeingKeyName(FeatureStore store, FeatureStore foreingStore) {
664
        try {
665
            for (FeatureAttributeDescriptor descriptor : store.getDefaultFeatureType()) {
666
                if (descriptor.isForeingKey()) {
667
                    ForeingKey foreingKey = descriptor.getForeingKey();
668
                    if (isTheSameStore(foreingStore, foreingKey.getFeatureStore(null))) {
669
                        return descriptor.getName();
670
                    }
671
                }
672
            }
673
        } catch (DataException ex) {
674
            return null;
675
        }
676
        return null;
686
    if (field.getPath().length > 2) {
687
      message.append("Invalid field '").append(field.getLabel()).append("'.\n");
688
      return false;
677 689
    }
678

  
679
    public boolean isValid(StringBuilder message) {
680
        Object value = this.getValue();
681
        if (value == null) {
682
            return true;
683
        }
684
        Field field = this.getCurrentField();
685
        if (field == null) {
686
            return true;
687
        }
688
        if (field.getPath().length > 2) {
689
            message.append("Invalid field '").append(field.getLabel()).append("'.\n");
690
            return false;
691
        }
692
        FeatureAttributeDescriptor descriptor = field.getDescriptor();
693
        switch (this.getRelationalOperator()) {
694
            case ExpressionBuilder.OPERATOR_EQ:
695
            case ExpressionBuilder.OPERATOR_NE:
696
            case ExpressionBuilder.OPERATOR_GT:
697
            case ExpressionBuilder.OPERATOR_GE:
698
            case ExpressionBuilder.OPERATOR_LT:
699
            case ExpressionBuilder.OPERATOR_LE:
690
    FeatureAttributeDescriptor descriptor = field.getDescriptor();
691
    switch (this.getRelationalOperator()) {
692
      case ExpressionBuilder.OPERATOR_EQ:
693
      case ExpressionBuilder.OPERATOR_NE:
694
      case ExpressionBuilder.OPERATOR_GT:
695
      case ExpressionBuilder.OPERATOR_GE:
696
      case ExpressionBuilder.OPERATOR_LT:
697
      case ExpressionBuilder.OPERATOR_LE:
700 698
        try {
701
                descriptor.getDataType().coerce(value);
702
            } catch (CoercionException ex) {
703
                message.append("Invalid value '")
704
                        .append(Objects.toString(value))
705
                        .append("' for field '")
706
                        .append(descriptor.getLabel())
707
                        .append("'.");
708
                message.append("\n");
709
                message.append(ex.getMessage());
710
                message.append("\n");
711
                return false;
712
            }
713
            break;
699
        descriptor.getDataType().coerce(value);
700
      } catch (CoercionException ex) {
701
        message.append("Invalid value '")
702
                .append(Objects.toString(value))
703
                .append("' for field '")
704
                .append(descriptor.getLabel())
705
                .append("'.");
706
        message.append("\n");
707
        message.append(ex.getMessage());
708
        message.append("\n");
709
        return false;
710
      }
711
      break;
714 712

  
715
            default:
716
            case ExpressionBuilder.OPERATOR_ILIKE:
717
                break;
718
        }
719
        return true;
713
      default:
714
      case ExpressionBuilder.OPERATOR_ILIKE:
715
        break;
720 716
    }
717
    return true;
718
  }
721 719

  
722
    public ExpressionBuilder.Value getFilter() {
723
        ExpressionBuilder.Value filter = null;
720
  public ExpressionBuilder.Value getFilter() {
721
    ExpressionBuilder.Value filter = null;
724 722

  
725
        Object value = this.getValue();
726
        if (value == null) {
727
            return null;
728
        }
729
        Field field = this.getCurrentField();
730
        if (field == null) {
731
            return null;
732
        }
733
        if (field.getPath().length > 2) {
734
            // No soportado
735
            return null;
736
        }
737
        DataManager dataManager = DALLocator.getDataManager();
738
        DALExpressionBuilder builder = dataManager.createDALExpressionBuilder();
739
        FeatureAttributeDescriptor parentDescriptor = field.getParentDescriptor();
740
        FeatureAttributeDescriptor descriptor = field.getDescriptor();
723
    Object value = this.getValue();
724
    if (value == null) {
725
      return null;
726
    }
727
    Field field = this.getCurrentField();
728
    if (field == null) {
729
      return null;
730
    }
731
    if (field.getPath().length > 2) {
732
      // No soportado
733
      return null;
734
    }
735
    DataManager dataManager = DALLocator.getDataManager();
736
    DALExpressionBuilder builder = dataManager.createDALExpressionBuilder();
737
    FeatureAttributeDescriptor parentDescriptor = field.getParentDescriptor();
738
    FeatureAttributeDescriptor descriptor = field.getDescriptor();
741 739

  
742
        ExpressionBuilder.Constant value_constant = null;
740
    ExpressionBuilder.Constant value_constant = null;
743 741

  
744
        switch (this.getRelationalOperator()) {
745
            case ExpressionBuilder.OPERATOR_EQ:
746
            case ExpressionBuilder.OPERATOR_NE:
747
            case ExpressionBuilder.OPERATOR_GT:
748
            case ExpressionBuilder.OPERATOR_GE:
749
            case ExpressionBuilder.OPERATOR_LT:
750
            case ExpressionBuilder.OPERATOR_LE:
742
    switch (this.getRelationalOperator()) {
743
      case ExpressionBuilder.OPERATOR_EQ:
744
      case ExpressionBuilder.OPERATOR_NE:
745
      case ExpressionBuilder.OPERATOR_GT:
746
      case ExpressionBuilder.OPERATOR_GE:
747
      case ExpressionBuilder.OPERATOR_LT:
748
      case ExpressionBuilder.OPERATOR_LE:
751 749
        try {
752
                value_constant = builder.expression().constant(
753
                        descriptor.getDataType().coerce(value)
754
                );
755
            } catch (CoercionException ex) {
756
                return null;
757
            }
758
            break;
750
        value_constant = builder.expression().constant(
751
                descriptor.getDataType().coerce(value)
752
        );
753
      } catch (CoercionException ex) {
754
        return null;
755
      }
756
      break;
759 757

  
760
            default:
761
            case ExpressionBuilder.OPERATOR_ILIKE:
762
                value_constant = builder.expression().constant(value);
763
                break;
764
        }
758
      default:
759
      case ExpressionBuilder.OPERATOR_ILIKE:
760
        value_constant = builder.expression().constant(value);
761
        break;
762
    }
765 763

  
766
        if (parentDescriptor == null) {
767
            // Se busca en campos de la misma tabla.
768
            filter = builder.expression().binaryOperator(
769
                    this.getRelationalOperator(),
770
                    builder.expression().column(descriptor.getName()),
771
                    value_constant
772
            );
773
        } else {
774
            // Se busca en campos de una tabla relacionada.
775
            switch (parentDescriptor.getRelationType()) {
776
                case DynField.RELATION_TYPE_COLLABORATION:
777
                case DynField.RELATION_TYPE_IDENTITY:
778
                    filter = builder.expression().binaryOperator(
779
                            this.getRelationalOperator(),
780
                            builder.foreing_value(
781
                                    parentDescriptor.getName(),
782
                                    descriptor.getName()
783
                            ),
784
                            value_constant
785
                    );
786
                    break;
764
    if (parentDescriptor == null) {
765
      // Se busca en campos de la misma tabla.
766
      filter = builder.expression().binaryOperator(
767
              this.getRelationalOperator(),
768
              builder.expression().column(this.store.getName(),descriptor.getName()),
769
              value_constant
770
      );
771
    } else {
772
      // Se busca en campos de una tabla relacionada.
773
      switch (parentDescriptor.getRelationType()) {
774
        case DynField.RELATION_TYPE_COLLABORATION:
775
        case DynField.RELATION_TYPE_IDENTITY:
776
          filter = builder.expression().binaryOperator(
777
                  this.getRelationalOperator(),
778
                  builder.foreing_value(
779
                          parentDescriptor.getName(),
780
                          descriptor.getName()
781
                  ),
782
                  value_constant
783
          );
784
          break;
787 785

  
788
                case DynField.RELATION_TYPE_AGGREGATE:
789
                case DynField.RELATION_TYPE_COMPOSITION:
790
                    filter = builder.exists(builder.select()
791
                            .column(parentDescriptor.getFeatureType().getPrimaryKey()[0].getName())
792
                            .from(field.getFeatureStore().getName())
793
                            .limit(1)
794
                            .where(
795
                                    builder.expression().and(
796
                                            builder.expression().eq(
797
                                                    builder.expression().getattr(
798
                                                            field.getFeatureStore().getName(),
799
                                                            getForeingKeyName(field.getFeatureStore(), this.store)
800
                                                    ),
801
                                                    builder.expression().getattr(
802
                                                            this.store.getName(),
803
                                                            getPrimaryKeyName(this.store)
804
                                                    )
805
                                            ),
806
                                            builder.expression().binaryOperator(
807
                                                    this.getRelationalOperator(),
808
                                                    builder.expression().column(descriptor.getName()),
809
                                                    value_constant
810
                                            )
811
                                    )
812
                            )
813
                            .toValue()
814
                    );
815
                    break;
816
            }
817
        }
818
        return filter;
786
        case DynField.RELATION_TYPE_AGGREGATE:
787
        case DynField.RELATION_TYPE_COMPOSITION:
788
          filter = builder.exists(builder.select()
789
                  .column(parentDescriptor.getFeatureType().getPrimaryKey()[0].getName())
790
                  .from(field.getFeatureStore().getName())
791
                  .limit(1)
792
                  .where(
793
                          builder.expression().and(
794
                                  builder.expression().eq(
795
                                          builder.expression().column(
796
                                                  field.getFeatureStore().getName(),
797
                                                  getForeingKeyName(field.getFeatureStore(), this.store)
798
                                          ),
799
                                          builder.expression().column(
800
                                                  this.store.getName(),
801
                                                  getPrimaryKeyName(this.store)
802
                                          )
803
                                  ),
804
                                  builder.expression().binaryOperator(
805
                                          this.getRelationalOperator(),
806
                                          builder.expression().column(this.store.getName(),descriptor.getName()),
807
                                          value_constant
808
                                  )
809
                          )
810
                  )
811
                  .toValue()
812
          );
813
          break;
814
      }
819 815
    }
816
    return filter;
817
  }
820 818

  
821
    public JsonObject toJson() {
822
        JsonObjectBuilder fieldBuilder = Json.createObjectBuilder();
819
  public JsonObject toJson() {
820
    JsonObjectBuilder fieldBuilder = Json.createObjectBuilder();
823 821

  
824
        JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
825
        for (FeatureAttributeDescriptor featureAttributeDescriptor : this.getCurrentField().getPath()) {
826
            JsonArrayBuilder pathArray = Json.createArrayBuilder();
822
    JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
823
    for (FeatureAttributeDescriptor featureAttributeDescriptor : this.getCurrentField().getPath()) {
824
      JsonArrayBuilder pathArray = Json.createArrayBuilder();
827 825

  
828
            //first value: name field
829
            String fieldName = featureAttributeDescriptor.getName();
830
            pathArray.add(fieldName);
831
            //second value: name store
832
            String storeName = featureAttributeDescriptor.getFeatureType().getStore().getName();
833
            pathArray.add(storeName);
826
      //first value: name field
827
      String fieldName = featureAttributeDescriptor.getName();
828
      pathArray.add(fieldName);
829
      //second value: name store
830
      String storeName = featureAttributeDescriptor.getFeatureType().getStore().getName();
831
      pathArray.add(storeName);
834 832

  
835
            arrayBuilder.add(pathArray.build());
836
        }
837
        String relational = this.getRelationalOperator();
838
        Object value = this.getValue();
839
        String strValue = DataTypeUtils.toString(value);
840
        String logical = this.getLogicalOperator();
833
      arrayBuilder.add(pathArray.build());
834
    }
835
    String relational = this.getRelationalOperator();
836
    Object value = this.getValue();
837
    String strValue = DataTypeUtils.toString(value);
838
    String logical = this.getLogicalOperator();
841 839

  
842
        fieldBuilder.add("fieldPath", arrayBuilder.build());
843
        fieldBuilder.add("relational", relational);
844
        if (!StringUtils.isEmpty(strValue)) {
845
            fieldBuilder.add("strValue", strValue);
846
        }
847
        if (!StringUtils.isEmpty(logical)) {
848
            fieldBuilder.add("logical", logical);
849
        }
850
        return fieldBuilder.build();
840
    fieldBuilder.add("fieldPath", arrayBuilder.build());
841
    fieldBuilder.add("relational", relational);
842
    if (!StringUtils.isEmpty(strValue)) {
843
      fieldBuilder.add("strValue", strValue);
851 844
    }
845
    if (!StringUtils.isEmpty(logical)) {
846
      fieldBuilder.add("logical", logical);
847
    }
848
    return fieldBuilder.build();
849
  }
852 850

  
853
    public void fromJson(JsonObject jsonState) {
854
        if (jsonState == null) {
855
            return;
856
        }
851
  public void fromJson(JsonObject jsonState) {
852
    if (jsonState == null) {
853
      return;
854
    }
857 855

  
858
        JsonArray fieldPath = jsonState.getJsonArray("fieldPath");
856
    JsonArray fieldPath = jsonState.getJsonArray("fieldPath");
859 857

  
860
        // array of arrays
861
        String[][] arrayNew = new String[fieldPath.size()][2];
862
        for (int i = 0; i < fieldPath.size(); i++) {
863
            String[] arrayField = new String[2];
864
            arrayField[0] = fieldPath.getJsonArray(i).getString(0);
865
            arrayField[1] = fieldPath.getJsonArray(i).getString(1);
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff