Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.plugin / org.gvsig.daltransform.app / org.gvsig.daltransform.app.join / src / main / java / org / gvsig / app / join / dal / feature / JoinTransform.java @ 44978

History | View | Annotate | Download (20.3 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.app.join.dal.feature;
25

    
26
import java.util.ArrayList;
27
import java.util.Arrays;
28
import java.util.HashMap;
29
import java.util.Iterator;
30
import java.util.List;
31
import java.util.Map;
32
import java.util.Map.Entry;
33
import java.util.Objects;
34
import java.util.logging.Level;
35
import org.apache.commons.lang3.StringUtils;
36
import org.gvsig.fmap.dal.DataTypes;
37

    
38
import org.gvsig.fmap.dal.exception.DataException;
39
import org.gvsig.fmap.dal.feature.AbstractFeatureStoreTransform;
40
import org.gvsig.fmap.dal.feature.EditableFeature;
41
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
42
import org.gvsig.fmap.dal.feature.EditableFeatureType;
43
import org.gvsig.fmap.dal.feature.Feature;
44
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
45
import org.gvsig.fmap.dal.feature.FeatureQuery;
46
import org.gvsig.fmap.dal.feature.FeatureSet;
47
import org.gvsig.fmap.dal.feature.FeatureStore;
48
import org.gvsig.fmap.dal.feature.FeatureType;
49
import org.gvsig.fmap.dal.feature.exception.SetReadOnlyAttributeException;
50
import org.gvsig.tools.ToolsLocator;
51
import org.gvsig.tools.dataTypes.Coercion;
52
import org.gvsig.tools.dataTypes.CoercionContext;
53
import org.gvsig.tools.dataTypes.CoercionException;
54
import org.gvsig.tools.dataTypes.DataType;
55
import org.gvsig.tools.dispose.DisposableIterator;
56
import org.gvsig.tools.dynobject.DynStruct;
57
import org.gvsig.tools.evaluator.Evaluator;
58
import org.gvsig.tools.evaluator.EvaluatorData;
59
import org.gvsig.tools.evaluator.EvaluatorException;
60
import org.gvsig.tools.evaluator.EvaluatorFieldsInfo;
61
import org.gvsig.tools.observer.Observer;
62
import org.gvsig.tools.persistence.PersistenceManager;
63
import org.gvsig.tools.persistence.PersistentState;
64
import org.gvsig.tools.persistence.exception.PersistenceException;
65
import org.slf4j.Logger;
66
import org.slf4j.LoggerFactory;
67

    
68
public class JoinTransform
69
    extends AbstractFeatureStoreTransform {
70

    
71
    private static final Logger logger = LoggerFactory.getLogger(JoinTransform.class);
72

    
73
    public static final String PERSISTENCE_DEFINITION_NAME = "JoinTransform";
74

    
75
    /**
76
     * Store from which the join transform will get the additional attributes
77
     */
78
    private FeatureStore store2;
79

    
80
    /**
81
     * name of the key attr in store1 that will be used to match features in
82
     * store2
83
     */
84
    private String keyAttr1;
85

    
86
    /**
87
     * name of the key attr in store2 that will be used to match features in
88
     * store1
89
     */
90
    private String keyAttr2;
91

    
92
    /**
93
     * names of the attributes to join from store2 to store1
94
     */
95
    private String[] attrs;
96

    
97
    /**
98
     * Attribute names may change after transformation a prefix is applied. This
99
     * map keeps correspondence between store1 original names and their
100
     * transformed counterparts.
101
     */
102
    private final Map<String, String> store1NamesMap;
103

    
104
    /**
105
     * Attribute names may change after transformation if they are repeated in
106
     * both stores or if a prefix is applied. This map keeps correspondence
107
     * between store2 original names and their transformed counterparts.
108
     */
109
    private final Map<String, String> store2NamesMap;
110

    
111
    private JoinTransformEvaluator evaluator = null;
112

    
113
    private FeatureType originalFeatureType;
114

    
115
    private String[] attrsForQuery;
116

    
117
    private String prefix1;
118

    
119
    private String prefix2;
120
    
121
    private CoercionContext attr1Context;
122

    
123
    /**
124
     * A default constructor
125
     */
126
    public JoinTransform() {
127
        store1NamesMap = new HashMap<>();
128
        store2NamesMap = new HashMap<>();
129
    }
130

    
131
    /**
132
     * Initializes all the necessary data for this transform
133
     *
134
     * @param store1 store whose default feature type is the target of this
135
     * transform
136
     *
137
     * @param store2 store whose default feature type will provide the new
138
     * attributes to join
139
     *
140
     * @param keyAttr1 key attribute in store1 that matches keyAttr2 in store2
141
     * (foreign key), used for joining both stores.
142
     *
143
     * @param keyAttr2 key attribute in store2 that matches keyAttr1 in store2
144
     * (foreign key), used for joining both stores.
145
     * @param prefix1
146
     * @param prefix2
147
     *
148
     * @param attrs names of the attributes in store2 that will be joined to
149
     * store1.
150
     */
151
    public void setValues(FeatureStore store1, FeatureStore store2,
152
        String keyAttr1, String keyAttr2, String prefix1, String prefix2,
153
        String[] attrs) {
154

    
155
        if( store1 == store2 ) {
156
            throw new IllegalArgumentException("store1 == store2");
157
        }
158

    
159
        this.setFeatureStore(store1);
160
        this.store2 = store2;
161
        this.keyAttr1 = keyAttr1;
162
        this.keyAttr2 = keyAttr2;
163
        this.prefix1 = prefix1; // TODO
164
        this.prefix2 = prefix2; // TODO
165
        this.attrs = attrs;
166
        this.attr1Context = store1.getDefaultFeatureTypeQuietly().getAttributeDescriptor(this.keyAttr1).getCoercionContext();
167

    
168
    }
169

    
170
    private boolean containsIgnoreCase(List<String>l, String item) {
171
        for (String x : l) {
172
            if( StringUtils.equalsIgnoreCase(item, x) ) {
173
                return true;
174
            }
175
        }
176
        return false;
177
    }
178
    
179
    @Override
180
    public void setUp() throws Exception {
181

    
182
        // calculate this transform resulting feature type
183
        // by adding all specified attrs from store2 to store1's default
184
        // feature type
185
        // FIXME for more than one FTypes ??
186
        this.originalFeatureType = this.getFeatureStore().getDefaultFeatureType();
187

    
188
        // keep index of geometry and att desc ==============
189
        int orig_geom_field_index
190
            = this.originalFeatureType.getDefaultGeometryAttributeIndex();
191
        FeatureAttributeDescriptor orig_geom_field_att
192
            = this.originalFeatureType.getDefaultGeometryAttribute();
193

    
194
        // Create the feature type and copy the store 1 type        
195
        EditableFeatureType editableFeatureType = this.getFeatureStore().getDefaultFeatureType().getEditable();
196
        FeatureAttributeDescriptor[] featureAttributeDescriptors = editableFeatureType.getAttributeDescriptors();
197
        for( int i = 0; i < featureAttributeDescriptors.length; i++ ) {
198
            editableFeatureType.remove(featureAttributeDescriptors[i].getName());
199
        }
200
        addFeatureType(editableFeatureType, featureAttributeDescriptors, prefix1, store1NamesMap);
201

    
202
        // =========== set the new geom field name and restore geometry values
203
        if( orig_geom_field_index >= 0 ) {
204
            EditableFeatureAttributeDescriptor ed_att = null;
205
            ed_att = (EditableFeatureAttributeDescriptor) editableFeatureType.getAttributeDescriptor(orig_geom_field_index);
206
            ed_att.setSRS(orig_geom_field_att.getSRS());
207
            ed_att.setObjectClass(orig_geom_field_att.getObjectClass());
208
            ed_att.setGeometryType(orig_geom_field_att.getGeomType());
209
            ed_att.setDefaultValue(orig_geom_field_att.getDefaultValue());
210

    
211
            String new_geom_field_name = ed_att.getName();
212
            editableFeatureType.setDefaultGeometryAttributeName(new_geom_field_name);
213
        }
214
        // =====================================================================
215

    
216
        // Add the store 2 fields    
217
        FeatureType featureType2 = store2.getDefaultFeatureType();
218

    
219
        // Add the fields       
220
        for( int i = 0; i < attrs.length; i++ ) {
221
            addFeatureType(editableFeatureType, featureType2.getAttributeDescriptor(attrs[i]), prefix2, store2NamesMap);
222
        }
223

    
224
        List<String> list1 = new ArrayList<>();
225
        for (String attr : this.attrs) {
226
            if( !containsIgnoreCase(list1, attr) ) {
227
                list1.add(attr);
228
            }
229
        }
230
        if( !containsIgnoreCase(list1, keyAttr2 ) ) {
231
            list1.add(keyAttr2);
232
        }
233
        List<String> list2 = new ArrayList<>(list1);
234
        for (String attrname : list1) {
235
            FeatureAttributeDescriptor attrdesc = featureType2.getAttributeDescriptor(attrname);
236
            String[] requiredAttrs = attrdesc.getRequiredFieldNames();
237
            if( requiredAttrs!=null ) {
238
                for (String requiredAttr : requiredAttrs) {
239
                    if( !containsIgnoreCase(list2, requiredAttr) ) {
240
                        list2.add(requiredAttr);
241
                    }
242
                }
243
            }
244
        }
245
        this.attrsForQuery = (String[]) list2.toArray(new String[]{});
246
//        if( this.store2NamesMap.containsKey(keyAttr2) ) {
247
//            this.attrsForQuery = this.attrs;
248
//        } else {
249
//            List<String> list = new ArrayList<String>(this.attrs.length + 1);
250
//            list.addAll(Arrays.asList(this.attrs));
251
//            list.add(keyAttr2);
252
//            this.attrsForQuery = (String[]) list.toArray(new String[]{});
253
//        }
254

    
255
        // assign calculated feature type as this transform's feature type
256
        FeatureType[] types = new FeatureType[]{
257
            editableFeatureType.getNotEditableCopy()};
258
        setFeatureTypes(Arrays.asList(types), types[0]);
259

    
260
        if( store2.getIndexes().getFeatureIndex(keyAttr2)==null ) {
261
            store2.createIndex(featureType2, keyAttr2, keyAttr2, (Observer)null);
262
        }
263
       
264
    }
265

    
266
    private void addFeatureType(EditableFeatureType targetFeatureType, FeatureAttributeDescriptor[] featureAttributeDescriptors,
267
        String prefix, Map<String, String> storeMap) throws DataException {
268

    
269
        for( int i = 0; i < featureAttributeDescriptors.length; i++ ) {
270
            addFeatureType(targetFeatureType, featureAttributeDescriptors[i], prefix, storeMap);
271
        }
272
    }
273

    
274
    private void addFeatureType(EditableFeatureType targetFeatureType, FeatureAttributeDescriptor featureAttributeDescriptor,
275
        String prefix, Map<String, String> storeMap) throws DataException {
276

    
277
        String attName = featureAttributeDescriptor.getName();
278
        if( (prefix != null) && (!prefix.equals("")) ) {
279
            attName = prefix + "_" + attName;
280
        }
281

    
282
        // If an attribute already exists, calculate an alternate name and add it to our type
283
        int j = 0;
284
        while( targetFeatureType.getIndex(attName) >= 0 ) {
285
            attName = targetFeatureType.getAttributeDescriptor(attName).getName() + "_" + ++j;
286
        }
287

    
288
        EditableFeatureAttributeDescriptor editableFeatureAttributeDescriptor
289
            = targetFeatureType.add(attName, featureAttributeDescriptor.getType(),
290
                featureAttributeDescriptor.getSize());
291
        editableFeatureAttributeDescriptor.setPrecision(featureAttributeDescriptor.getPrecision());
292
        if( featureAttributeDescriptor.getType() == DataTypes.GEOMETRY ) {
293
            editableFeatureAttributeDescriptor.setGeometryType(featureAttributeDescriptor.getGeomType());
294
        }
295
        // keep correspondence between original name and transformed name
296
        storeMap.put(featureAttributeDescriptor.getName(), attName);
297
    }
298

    
299
    /**
300
     *
301
     *
302
     * @param source
303
     *
304
     * @param target
305
     *
306
     * @throws DataException
307
     */
308
    @Override
309
    public void applyTransform(Feature source, EditableFeature target)
310
        throws DataException {
311

    
312
        // copy the data from store1 into the resulting feature
313
        this.copySourceToTarget(source, target);
314

    
315
        // ask store2 for the specified attributes, filtering by the key
316
        // attribute value
317
        // from the source feature
318
        JoinTransformEvaluator eval = this.getEvaluator();
319
        eval.updateValue(source.get(this.keyAttr1), this.attr1Context);
320

    
321
        FeatureQuery query = store2.createFeatureQuery();
322
        query.setAttributeNames(attrsForQuery);
323
        query.setFilter(eval);
324
        FeatureSet set = null;
325
        DisposableIterator itFeat = null;
326

    
327
        try {
328

    
329
            set = store2.getFeatureSet(query);
330
            // In this join implementation, we will take only the first matching
331
            // feature found in store2
332

    
333
            Feature feat;
334

    
335
            itFeat = set.fastIterator();
336
            if( itFeat.hasNext() ) {
337
                feat = (Feature) itFeat.next();
338

    
339
                // copy all attributes from joined feature to target
340
                this.copyJoinToTarget(feat, target);
341
            }
342
        } finally {
343
            if( itFeat != null ) {
344
                itFeat.dispose();
345
            }
346
            if( set != null ) {
347
                set.dispose();
348
            }
349
        }
350
    }
351

    
352
    /**
353
     * @param feat
354
     * @param target
355
     */
356
    private void copyJoinToTarget(Feature join, EditableFeature target) {
357
        Iterator<Entry<String, String>> iter = store2NamesMap.entrySet()
358
            .iterator();
359
        Entry<String, String> entry;
360
        FeatureType trgType = target.getType();
361
        FeatureAttributeDescriptor attr;
362
        while( iter.hasNext() ) {
363
            entry = iter.next();
364
            attr = trgType.getAttributeDescriptor((String) entry.getValue());
365
            if( attr != null && !attr.isReadOnly() ) {
366
                target.set(attr.getIndex(), join.get((String) entry.getKey()));
367
            }
368
        }
369
    }
370

    
371
    /**
372
     * @param source
373
     * @param target
374
     */
375
    private void copySourceToTarget(Feature source, EditableFeature target) {
376
        FeatureAttributeDescriptor attr, attrTrg;
377
        FeatureType ftSrc = source.getType();
378
        FeatureType ftTrg = target.getType();
379

    
380
        for( int i = 0; i < source.getType().size(); i++ ) {
381
            attr = ftSrc.getAttributeDescriptor(i);
382
            attrTrg = ftTrg.getAttributeDescriptor(store1NamesMap.get(attr.getName()));
383
            if( attrTrg != null ) {
384
                try {
385
                    if( !attrTrg.isReadOnly() ) {
386
                        target.set(attrTrg.getIndex(), source.get(i));
387
                    }
388
                } catch (SetReadOnlyAttributeException e1) {
389
                    // Ignore, do nothing
390

    
391
                } catch (IllegalArgumentException e) {
392
                    attrTrg = ftTrg.getAttributeDescriptor(attr.getName());
393
                    target.set(attrTrg.getIndex(), attrTrg.getDefaultValue());
394
                }
395

    
396
            }
397
        }
398

    
399
    }
400

    
401
    private JoinTransformEvaluator getEvaluator() {
402
        if( this.evaluator == null ) {
403
            FeatureType ft2 = null;
404
            try {
405
                ft2 = this.store2.getDefaultFeatureType();
406
            } catch (DataException e) {
407
                logger.warn("Can't access to the feature type to build the evaluator.", e);
408
                throw new RuntimeException("Can't access to the feature type to build the evaluator.", e);
409
            }
410
            FeatureAttributeDescriptor att2 = ft2.getAttributeDescriptor(keyAttr2);
411
            boolean is_num = att2.getDataType().isNumeric();
412
            this.evaluator = new JoinTransformEvaluator(keyAttr2, is_num);
413
        }
414
        return evaluator;
415

    
416
    }
417

    
418
    private class JoinTransformEvaluator
419
        implements Evaluator {
420

    
421
        private String attribute;
422
        private boolean isNumeric = false;
423
        private Object value;
424
        private String sql;
425
        private EvaluatorFieldsInfo info = null;
426
        private Coercion coercion;
427
        private CoercionContext context;
428

    
429
        //                private int attributeIndex;
430
        public JoinTransformEvaluator(String attribute, boolean is_numeric) {
431
            this.attribute = attribute;
432
            this.isNumeric = is_numeric;
433
            this.value = null;
434
            this.info = new EvaluatorFieldsInfo();
435

    
436
            //                        this.attributeIndex = attrIndex;
437
        }
438

    
439
        public void updateValue(Object value, CoercionContext context) {
440
            this.value = value;
441
            this.coercion = null;
442
            this.context = context;
443
            
444
            if (this.value!=null) {
445
                DataType dataType = ToolsLocator.getDataTypesManager().getDataType(value.getClass());
446
                if (dataType!=null) {
447
                    this.coercion = dataType.getCoercion();
448
                }
449
                String qt = this.isNumeric ? "" : "'";
450
                this.sql = this.attribute + " = " + qt + this.value + qt;
451
            } else {
452
                this.sql = this.attribute + " = null";
453
            }
454
            this.info = new EvaluatorFieldsInfo();
455
            this.info.addMatchFieldValue(this.attribute, value);
456
        }
457

    
458
        @Override
459
        public Object evaluate(EvaluatorData arg0) throws EvaluatorException {
460
            Object curValue = arg0.getDataValue(attribute);
461
            if( curValue == null ) {
462
                return value == null;
463
            }
464
            if ( value == null) {
465
                return false;
466
            }
467
            Object coerceValue;
468
            if (this.coercion == null) {
469
                return StringUtils.equals(Objects.toString(curValue), Objects.toString(value));
470
            }
471
            try {
472
                coerceValue = this.coercion.coerce(curValue, this.context);
473
                return coerceValue.equals(value);
474
            } catch (CoercionException ex) {
475
                return StringUtils.equals(Objects.toString(curValue), Objects.toString(value));
476
            }
477
        }
478

    
479
        @Override
480
        public String getSQL() {
481
            return this.sql;
482
        }
483

    
484
        @Override
485
        public String getDescription() {
486
            return "Evaluates join transform match";
487
        }
488

    
489
        @Override
490
        public String getName() {
491
            return "JoinTransformEvaluator";
492
        }
493

    
494
        @Override
495
        public EvaluatorFieldsInfo getFieldsInfo() {
496
            return this.info;
497
        }
498

    
499
    }
500

    
501
    @SuppressWarnings("unchecked")
502
    @Override
503
    public FeatureType getSourceFeatureTypeFrom(FeatureType arg0) {
504
        return originalFeatureType;
505
    }
506

    
507
    public static void registerPersistent() {
508
        PersistenceManager persistenceManager = ToolsLocator.getPersistenceManager();
509

    
510
        if( persistenceManager.getDefinition(AbstractFeatureStoreTransform.class) == null ) {
511
            AbstractFeatureStoreTransform.registerPersistent();
512
        }
513

    
514
        DynStruct definition = persistenceManager.getDefinition(PERSISTENCE_DEFINITION_NAME);
515

    
516
        if( definition == null ) {
517
            definition = persistenceManager.addDefinition(
518
                JoinTransform.class,
519
                PERSISTENCE_DEFINITION_NAME,
520
                "JoinTransform Persistence definition",
521
                null,
522
                null
523
            );
524
            definition.extend(PersistenceManager.PERSISTENCE_NAMESPACE,
525
                ABSTRACT_FEATURESTORE_DYNCLASS_NAME);
526

    
527
            definition.addDynFieldObject("store2").setClassOfValue(FeatureStore.class).setMandatory(true);
528
            definition.addDynFieldString("keyAttr1").setMandatory(true);
529
            definition.addDynFieldString("keyAttr2").setMandatory(true);
530
            definition.addDynFieldString("prefix1").setMandatory(false);
531
            definition.addDynFieldString("prefix2").setMandatory(false);
532
            definition.addDynFieldList("attrs").setClassOfItems(String.class).setMandatory(true);
533
        }
534
    }
535

    
536
    @Override
537
    public void saveToState(PersistentState state) throws PersistenceException {
538
        super.saveToState(state);
539
        state.set("store2", this.store2);
540
        state.set("keyAttr1", this.keyAttr1);
541
        state.set("keyAttr2", this.keyAttr2);
542
        state.set("prefix1", this.prefix1);
543
        state.set("prefix2", this.prefix2);
544
        state.set("attrs", this.attrs);
545
    }
546

    
547
    @Override
548
    public void loadFromState(PersistentState state) throws PersistenceException {
549
        super.loadFromState(state);
550
        store2 = (FeatureStore) state.get("store2");
551
        keyAttr1 = state.getString("keyAttr1");
552
        keyAttr2 = state.getString("keyAttr2");
553
        prefix1 = state.getString("prefix1");
554
        prefix2 = state.getString("prefix2");
555
        attrs = (String[]) state.getArray("attrs", String.class);
556
    }
557

    
558
}