Revision 9768

View differences:

org.gvsig.topology/tags/org.gvsig.topology-1.0.172/org.gvsig.topology.lib/org.gvsig.topology.lib.impl/src/main/java/org/gvsig/topology/lib/impl/TopologyImplLibrary.java
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.topology.lib.impl;
25

  
26
import org.gvsig.fmap.dal.DALLibrary;
27
import org.gvsig.fmap.geom.GeometryLibrary;
28
import org.gvsig.tools.ToolsLibrary;
29
import org.gvsig.tools.library.AbstractLibrary;
30
import org.gvsig.tools.library.LibraryException;
31
import org.gvsig.topology.lib.api.TopologyLibrary;
32
import org.gvsig.topology.lib.api.TopologyLocator;
33
import org.gvsig.topology.lib.impl.customizablerule.CustomizableRule0ActionsFactory;
34
import org.gvsig.topology.rule.GeometryIsValidFactory;
35
import org.gvsig.topology.rule.GeometryMustNotBeNullRuleFactory;
36
import org.gvsig.topology.rule.LineMustBeCoveredByBoundaryOfPolygonRuleFactory;
37
import org.gvsig.topology.rule.PolygonContainsPointRuleFactory;
38
import org.gvsig.topology.rule.LineMustBeLargerThanToleranceRuleFactory;
39
import org.gvsig.topology.rule.PolygonMustNotOverlapPolygonRuleFactory;
40
import org.gvsig.topology.rule.PointMustBeProperlyInsidePolygonRuleFactory;
41
import org.gvsig.topology.rule.PolygonContainsOnePointRuleFactory;
42
import org.gvsig.topology.rule.PolygonContainsPolygonRuleFactory;
43
import org.gvsig.topology.rule.PolygonMustBeCoveredByPolygonRuleFactory;
44
import org.gvsig.topology.rule.PolygonMustNotOverlapWithPolygonRuleFactory;
45

  
46
/**
47
 *
48
 * @author jjdelcerro
49
 */
50
public class TopologyImplLibrary extends AbstractLibrary {
51

  
52
    @Override
53
    public void doRegistration() {
54
        super.doRegistration();
55
        registerAsImplementationOf(TopologyLibrary.class);
56
        this.require(ToolsLibrary.class);
57
        this.require(DALLibrary.class);
58
        this.require(GeometryLibrary.class);
59
    }
60

  
61
    @Override
62
    protected void doInitialize() throws LibraryException {
63
        TopologyLocator.registerDefaultTopologyManager(DefaultTopologyManager.class);
64
    }
65

  
66
    @Override
67
    protected void doPostInitialize() throws LibraryException {
68
        CustomizableRule0ActionsFactory.selfRegister();
69
        GeometryMustNotBeNullRuleFactory.selfRegister();
70
        LineMustBeCoveredByBoundaryOfPolygonRuleFactory.selfRegister();
71
        LineMustBeLargerThanToleranceRuleFactory.selfRegister();
72
        PointMustBeProperlyInsidePolygonRuleFactory.selfRegister();
73
        PolygonContainsPointRuleFactory.selfRegister();
74
        PolygonMustBeCoveredByPolygonRuleFactory.selfRegister();
75
        PolygonMustNotOverlapPolygonRuleFactory.selfRegister();
76
        PolygonContainsPolygonRuleFactory.selfRegister();
77
        PolygonContainsOnePointRuleFactory.selfRegister();
78
        PolygonMustNotOverlapWithPolygonRuleFactory.selfRegister();
79
        GeometryIsValidFactory.selfRegister();
80
    }
81

  
82
}
org.gvsig.topology/tags/org.gvsig.topology-1.0.172/org.gvsig.topology.lib/org.gvsig.topology.lib.impl/src/main/java/org/gvsig/topology/lib/impl/DefaultTopologyReportLine.java
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.topology.lib.impl;
25

  
26
import org.gvsig.fmap.dal.feature.FeatureReference;
27
import org.gvsig.fmap.geom.Geometry;
28
import org.gvsig.topology.lib.api.TopologyDataSet;
29
import org.gvsig.topology.lib.api.TopologyReport;
30
import org.gvsig.topology.lib.api.TopologyReportLine;
31
import org.gvsig.topology.lib.api.TopologyRule;
32

  
33
/**
34
 *
35
 * @author jjdelcerro
36
 */
37
public class DefaultTopologyReportLine implements TopologyReportLine {
38
    
39
    private final TopologyReport report;
40
    private final TopologyRule rule;
41
    private final TopologyDataSet dataSet1;
42
    private final TopologyDataSet dataSet2;
43
    private final Geometry geometry;
44
    private final FeatureReference feature1;
45
    private final FeatureReference feature2;
46
    private final int primitive1;
47
    private final int primitive2;
48
    private boolean exception;
49
    private final String description;
50
    private final String data;
51
    private final Geometry errorGeometry;
52
    
53
    DefaultTopologyReportLine(DefaultTopologyReport report, 
54
            TopologyRule rule, 
55
            TopologyDataSet dataSet1, 
56
            TopologyDataSet dataSet2, 
57
            Geometry geometry,
58
            Geometry error,
59
            FeatureReference feature1, 
60
            FeatureReference feature2, 
61
            int primitive1,
62
            int primitive2,
63
            boolean exception,
64
            String description,
65
            String data
66
        ) {
67
        this.report = report;
68
        this.rule = rule;
69
        this.dataSet1 = dataSet1;
70
        this.dataSet2 = dataSet2;
71
        this.geometry = geometry;
72
        this.feature1 = feature1;
73
        this.feature2 = feature2;
74
        this.primitive1 = primitive1;
75
        this.primitive2 = primitive2;
76
        this.exception = exception;
77
        this.description = description;
78
        this.errorGeometry = error;
79
        this.data = data;
80
    }
81

  
82
    @Override
83
    public TopologyRule getRule() {
84
        return this.rule;
85
    }
86

  
87
    @Override
88
    public TopologyDataSet getDataSet1() {
89
        return this.dataSet1;
90
    }
91

  
92
    @Override
93
    public TopologyDataSet getDataSet2() {
94
        return this.dataSet2;
95
    }
96

  
97
    @Override
98
    public Geometry getGeometry() {
99
        return this.geometry;
100
    }
101

  
102
    @Override
103
    public FeatureReference getFeature1() {
104
        return this.feature1;
105
    }
106

  
107
    @Override
108
    public FeatureReference getFeature2() {
109
        return this.feature2;
110
    }
111

  
112
    @Override
113
    public boolean isException() {
114
        return this.exception;
115
    }
116
    
117
    public void setException(boolean exception) {
118
        this.exception = exception;
119
    }
120

  
121
    @Override
122
    public String getDescription() {
123
        return description;
124
    }
125

  
126
    @Override
127
    public Geometry getError() {
128
        return this.errorGeometry;
129
    }
130

  
131
    @Override
132
    public int getPrimitiveNumber1() {
133
        return this.primitive1;
134
    }
135

  
136
    @Override
137
    public int getPrimitiveNumber2() {
138
        return this.primitive2;
139
    }
140

  
141
    @Override
142
    public String getData() {
143
        return this.data;
144
    }
145
}
org.gvsig.topology/tags/org.gvsig.topology-1.0.172/org.gvsig.topology.lib/org.gvsig.topology.lib.impl/src/main/java/org/gvsig/topology/lib/impl/DefaultTopologyDataSet.java
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.topology.lib.impl;
25

  
26
import java.util.Iterator;
27
import java.util.Map;
28
import javax.json.JsonObject;
29
import org.apache.commons.collections.IteratorUtils;
30
import org.apache.commons.lang3.StringUtils;
31
import org.apache.commons.lang3.mutable.MutableObject;
32
import org.gvsig.expressionevaluator.Expression;
33
import org.gvsig.expressionevaluator.ExpressionUtils;
34
import org.gvsig.expressionevaluator.GeometryExpressionBuilder;
35
import org.gvsig.expressionevaluator.GeometryExpressionUtils;
36
import org.gvsig.fmap.dal.DataStore;
37
import org.gvsig.fmap.dal.EditingNotification;
38
import org.gvsig.fmap.dal.EditingNotificationManager;
39
import org.gvsig.fmap.dal.exception.DataException;
40
import org.gvsig.fmap.dal.feature.EditableFeature;
41
import org.gvsig.fmap.dal.feature.Feature;
42
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
43
import org.gvsig.fmap.dal.feature.FeatureReference;
44
import org.gvsig.fmap.dal.feature.FeatureSet;
45
import org.gvsig.fmap.dal.feature.FeatureStore;
46
import org.gvsig.fmap.dal.feature.FeatureStoreProviderFactory;
47
import org.gvsig.fmap.dal.feature.FeatureType;
48
import org.gvsig.fmap.dal.swing.DALSwingLocator;
49
import org.gvsig.fmap.geom.Geometry;
50
import org.gvsig.fmap.geom.GeometryLocator;
51
import org.gvsig.fmap.geom.GeometryManager;
52
import org.gvsig.fmap.geom.GeometryUtils;
53
import org.gvsig.fmap.geom.SpatialIndex;
54
import org.gvsig.fmap.geom.type.GeometryType;
55
import org.gvsig.json.Json;
56
import org.gvsig.json.JsonObjectBuilder;
57
import org.gvsig.tools.dispose.DisposableIterator;
58
import org.gvsig.tools.exception.BaseException;
59
import org.gvsig.tools.util.PropertiesSupportHelper;
60
import org.gvsig.tools.visitor.VisitCanceledException;
61
import org.gvsig.tools.visitor.Visitor;
62
import org.gvsig.topology.lib.api.CancelOperationException;
63
import org.gvsig.topology.lib.api.PerformOperationException;
64
import org.gvsig.topology.lib.api.TopologyDataSet;
65
import org.gvsig.topology.lib.api.TopologyLocator;
66
import org.gvsig.topology.lib.api.TopologyManager;
67
import org.gvsig.topology.lib.api.TopologyServices;
68
import org.slf4j.Logger;
69
import org.slf4j.LoggerFactory;
70

  
71
/**
72
 *
73
 * @author jjdelcerro
74
 */
75
@SuppressWarnings({"EqualsAndHashcode","UseSpecificCatch"})
76
public class DefaultTopologyDataSet implements TopologyDataSet {
77

  
78
    private final static Logger LOGGER = LoggerFactory.getLogger(DefaultTopologyDataSet.class);
79
    
80
    private TopologyServices services;
81
    private String name;
82
    private DataStore store;
83
    private boolean needFinishEditing;
84
    private String fullName;
85
    private PropertiesSupportHelper propertiesHelper;
86
    private MutableObject<SpatialIndex> spatialIndex = null;
87
    
88
    public DefaultTopologyDataSet() {
89
        this.services = null;
90
        this.name = null;
91
        this.store = null;
92
        this.needFinishEditing = false;
93
        this.fullName = null;
94
        this.propertiesHelper = new PropertiesSupportHelper();
95
    }
96

  
97
    public DefaultTopologyDataSet(TopologyServices services, String name, DataStore store) {
98
        this.services = services;
99
        this.name = name;
100
        this.store = store;
101
        this.needFinishEditing = false;
102
        if( store!=null ) {
103
            this.fullName = store.getFullName();
104
        }
105
    }
106

  
107
    @Override
108
    public void restart() {
109
        this.store  = null;
110
        this.spatialIndex = null;
111
    }
112
    
113
    @Override
114
    public boolean equals(Object obj) {
115
        if( !(obj instanceof DefaultTopologyDataSet) ) {
116
            return false;
117
        }
118
        DefaultTopologyDataSet other = (DefaultTopologyDataSet)obj;
119
        if( this.store != other.store ) {
120
            return false;
121
        }
122
        if( !StringUtils.equals(this.getName(), other.getName()) ) {
123
            return false;
124
        }
125
        return true;
126
    }
127

  
128
    @Override
129
    public String getName() {
130
        return this.name;
131
    }
132

  
133
    @Override
134
    public void setName(String name) {
135
        this.name = name;
136
    }
137

  
138
    @Override
139
    public String toString() {
140
        try {
141
            FeatureAttributeDescriptor attr = this.getFeatureStore().getDefaultFeatureType().getDefaultGeometryAttribute();
142
            String geomType = attr.getGeomType().getName();
143
            return this.name + " ("+ geomType + ")";
144
        } catch(Exception ex) {
145
            return this.name ;
146
        }
147
    }
148

  
149
    @Override
150
    public void setStore(DataStore store) {
151
        this.store = store;
152
    }
153

  
154
    @Override
155
    public DataStore getStore() {
156
        if (this.store == null) {
157
            this.store = this.services.getFeatureStore(this);
158
        }
159
        return this.store;
160
    }
161

  
162
    @Override
163
    public FeatureStore getFeatureStore() {
164
        if (this.store == null) {
165
            this.store = this.services.getFeatureStore(this);
166
        }
167
        return (FeatureStore) this.store;
168
    }
169

  
170
    @Override
171
    public long getSize() {
172
        try {
173
            long size = this.getFeatureStore().getFeatureCount();
174
            return size;
175
        } catch (DataException ex) {
176
            // TODO: mensage al log
177
            return 0;
178
        }
179
    }
180

  
181
    @Override
182
    public boolean isThisStore(FeatureStore store) {
183
        if( store == null ) {
184
            return false;
185
        }
186
        return StringUtils.equals(this.fullName, store.getFullName());
187
    }
188
    
189
    @Override
190
    public int getGeometryType() {
191
        try {
192
            FeatureStore theStore = this.getFeatureStore();
193
            FeatureType featureType = theStore.getDefaultFeatureType();
194
            FeatureAttributeDescriptor attr = featureType.getDefaultGeometryAttribute();
195
            GeometryType geomType = attr.getGeomType();
196
            return geomType.getType();
197
        } catch (Exception ex) {
198
            return Geometry.TYPES.GEOMETRY;
199
        }
200
    }
201

  
202
    @Override
203
    public void accept(Visitor visitor) throws VisitCanceledException {
204
        FeatureStore st = this.getFeatureStore();
205
        try {
206
            st.accept(visitor);
207
        } catch(VisitCanceledException ex) {
208
            throw ex;
209
        } catch(BaseException ex) {
210
            throw new RuntimeException(ex);
211
        }
212
    }
213

  
214
    @Override
215
    public void edit() throws DataException {
216
        FeatureStore theStore = this.getFeatureStore();
217
        if (!theStore.isEditing()) {
218
            theStore.edit();
219
            this.needFinishEditing = true;
220
        }
221
    }
222

  
223
    @Override
224
    public void finishEditing() throws DataException {
225
        if (this.needFinishEditing) {
226
            this.getFeatureStore().finishEditing();
227
        }
228
    }
229

  
230
    @Override
231
    public EditableFeature createNewFeature() throws DataException {
232
        EditableFeature f = this.getFeatureStore().createNewFeature();
233
        return f;
234
    }
235

  
236
    public void perform(
237
            String operation,
238
            Feature feature
239
    ) throws DataException {
240
        this.edit();
241

  
242
        EditingNotificationManager editingNotificationManager
243
                = DALSwingLocator.getEditingNotificationManager();
244
        FeatureStore theStore = this.getFeatureStore();
245
        
246
        EditingNotification notification
247
                = editingNotificationManager.notifyObservers(this, // source
248
                        operation, // type
249
                        null,// document
250
                        null,// layer
251
                        theStore,// store
252
                        feature// feature
253
                );
254

  
255
        if (notification.isCanceled()) {
256
            String msg = String.format(
257
                    "Can't insert feature into %1$s, canceled by some observer.",
258
                    this.getName());
259
            throw new CancelOperationException(msg);
260
        }
261
        
262
        String after = null;
263
        if( operation.equalsIgnoreCase(EditingNotification.BEFORE_REMOVE_FEATURE) ) {
264
            theStore.delete(feature);
265
            after = EditingNotification.AFTER_REMOVE_FEATURE;
266
            
267
        } else {
268
            if (notification.shouldValidateTheFeature()) {
269
                if (!editingNotificationManager.validateFeature(feature)) {
270
                    String msg = String.format("%1$s is not valid", feature.toString());
271
                    throw new PerformOperationException(msg);
272
                }
273
            }
274
            switch(operation) {
275
                case EditingNotification.BEFORE_UPDATE_FEATURE:
276
                    theStore.update((EditableFeature) feature);
277
                    after = EditingNotification.AFTER_UPDATE_FEATURE;
278
                    break;
279

  
280
                case EditingNotification.BEFORE_INSERT_FEATURE:
281
                    theStore.insert((EditableFeature) feature);
282
                    after = EditingNotification.AFTER_INSERT_FEATURE;
283
                    break;
284
            }
285
        }
286

  
287
        editingNotificationManager.notifyObservers(this,
288
                after, null, null,
289
                theStore, feature);
290

  
291
    }
292

  
293
    @Override
294
    public void insert(final EditableFeature feature) throws DataException {
295
        perform(
296
            EditingNotification.BEFORE_INSERT_FEATURE,
297
            feature
298
        );
299
    }
300

  
301
    @Override
302
    public void update(final EditableFeature feature) throws DataException {
303
        perform(
304
            EditingNotification.BEFORE_UPDATE_FEATURE,
305
            feature
306
        );
307
    }
308

  
309
    @Override
310
    public void delete(final Feature feature) throws DataException {
311
        perform(
312
            EditingNotification.BEFORE_REMOVE_FEATURE,
313
            feature
314
        );
315
    }
316

  
317
    @Override
318
    public void delete(final FeatureReference feature) throws DataException {
319
        perform(
320
            EditingNotification.BEFORE_REMOVE_FEATURE,
321
            feature.getFeature()
322
        );
323
    }
324

  
325
    @Override
326
    public JsonObject toJson() {
327
        return this.toJsonBuilder().build();
328
    }
329

  
330
    @Override
331
    public JsonObjectBuilder toJsonBuilder() {
332
        JsonObjectBuilder jsonDataSet = Json.createObjectBuilder();
333
        jsonDataSet.add("name", this.name);
334
        jsonDataSet.add("fullName", this.fullName);
335

  
336
        return jsonDataSet;
337
    }
338

  
339
    @Override
340
    public void fromJson(JsonObject json) {
341
        TopologyManager manager = TopologyLocator.getTopologyManager();
342
        this.name = json.getString("name");
343
        this.fullName = null;
344
        if( json.containsKey("fullName") ) {
345
            this.fullName = json.getString("fullName");
346
        }
347
        this.store = null;
348
        this.needFinishEditing = false;
349
        this.services = manager.getDefaultServices();
350
    }
351

  
352
    @Override
353
    public Object getProperty(String string) {
354
        return this.propertiesHelper.getProperty(name);
355
    }
356

  
357
    @Override
358
    public void setProperty(String string, Object o) {
359
        this.propertiesHelper.setProperty(name, o);
360
    }
361

  
362
    @Override
363
    public Map<String, Object> getProperties() {
364
        return this.propertiesHelper.getProperties();
365
    }
366

  
367
    @Override
368
    public SpatialIndex getSpatialIndex() {
369
        if( this.spatialIndex == null ) {
370
            this.spatialIndex = new MutableObject<>();
371
            FeatureStore theStore = this.getFeatureStore();
372
            FeatureStoreProviderFactory storeFactory = (FeatureStoreProviderFactory) theStore.getProviderFactory();
373
            if( storeFactory.useLocalIndexesCanImprovePerformance()==FeatureStoreProviderFactory.YES ) {
374
                try {
375
                    GeometryManager geomManager = GeometryLocator.getGeometryManager();
376
                    final SpatialIndex geomIndex = geomManager.createSpatialIndex(
377
                            GeometryManager.SPATIALINDEX_DEFAULT_QUADTREE,
378
                            null
379
                    );
380
                    final SpatialIndex dataIndex = theStore.wrapSpatialIndex(geomIndex);
381
                    try {
382
                        store.accept((Object o) -> {
383
                            Feature f = (Feature) o;
384
                            Geometry geom = f.getDefaultGeometry();
385
                            if (geom != null) {
386
                                dataIndex.insert(geom, f);
387
                            }
388
                        });
389
                    } catch (VisitCanceledException ex) {
390
                    }
391
                    this.spatialIndex.setValue(dataIndex);
392
                } catch (Exception ex) {
393
                    LOGGER.warn("Can't create spatial index", ex);
394
                }
395
            }
396
        }
397
        return this.spatialIndex.getValue();
398
    }
399

  
400
    @Override
401
    public Iterable<FeatureReference> query(Geometry geom) {
402
        return this.queryReferences(geom);
403
    }
404
    
405
    @Override
406
    public Iterable<FeatureReference> queryReferences(Geometry geom) {
407
        SpatialIndex index = this.getSpatialIndex();
408
        if( index == null ) {
409
            try {
410
                FeatureStore theStore = (FeatureStore) this.getStore();
411
                Expression expression = ExpressionUtils.createExpression();
412
                GeometryExpressionBuilder expressionBuilder = GeometryExpressionUtils.createExpressionBuilder();
413
                String geomName = theStore.getDefaultFeatureType().getDefaultGeometryAttributeName();
414
                if( GeometryUtils.isSubtype(Geometry.TYPES.POINT, geom.getType()) )  {
415
                    expression.setPhrase(
416
                        expressionBuilder.ifnull(
417
                            expressionBuilder.column(geomName),
418
                            expressionBuilder.constant(false),
419
                            expressionBuilder.ST_Intersects(
420
                                    expressionBuilder.column(geomName),
421
                                    expressionBuilder.geometry(geom)
422
                            )
423
                        ).toString()
424
                    );
425
                } else {
426
                    expression.setPhrase(
427
                        expressionBuilder.ifnull(
428
                            expressionBuilder.column(geomName),
429
                            expressionBuilder.constant(false),
430
                            expressionBuilder.ST_Overlaps(
431
                                    expressionBuilder.column(geomName),
432
                                    expressionBuilder.envelope(geom.getEnvelope())
433
                            )
434
                        ).toString()
435
                    );
436
                }
437
                FeatureSet set = theStore.getFeatureSet(expression);
438
                final DisposableIterator it = set.fastIterator();
439
                return () -> new Iterator<FeatureReference>() {
440
                    @Override
441
                    public boolean hasNext() {
442
                        return it.hasNext();
443
                    }
444
                    
445
                    @Override
446
                    public FeatureReference next() {
447
                        Feature f = (Feature) it.next();
448
                        return f.getReference();
449
                    }
450
                };
451
                
452
            } catch(Exception ex) {
453
                return (Iterable<FeatureReference>) IteratorUtils.EMPTY_ITERATOR;
454
            }
455
        }
456
        final Iterator it = index.query(geom);
457
        if( it == null ) {
458
            return (Iterable<FeatureReference>) IteratorUtils.EMPTY_ITERATOR;
459
        }
460
        return () -> it;
461
    }
462

  
463
    @Override
464
    public Iterable<Feature> queryFeatures(Geometry geom) {
465
        SpatialIndex index = this.getSpatialIndex();
466
        if( index == null ) {
467
            try {
468
                FeatureStore theStore = (FeatureStore) this.getStore();
469
                Expression expression = ExpressionUtils.createExpression();
470
                GeometryExpressionBuilder expressionBuilder = GeometryExpressionUtils.createExpressionBuilder();
471
                String geomName = theStore.getDefaultFeatureType().getDefaultGeometryAttributeName();
472
                if( GeometryUtils.isSubtype(Geometry.TYPES.POINT, geom.getType()) )  {
473
                    expression.setPhrase(
474
                        expressionBuilder.ifnull(
475
                            expressionBuilder.column(geomName),
476
                            expressionBuilder.constant(false),
477
                            expressionBuilder.ST_Intersects(
478
                                    expressionBuilder.column(geomName),
479
                                    expressionBuilder.geometry(geom)
480
                            )
481
                        ).toString()
482
                    );
483
                } else {
484
                    expression.setPhrase(
485
                        expressionBuilder.ifnull(
486
                            expressionBuilder.column(geomName),
487
                            expressionBuilder.constant(false),
488
                            expressionBuilder.ST_Overlaps(
489
                                    expressionBuilder.column(geomName),
490
                                    expressionBuilder.envelope(geom.getEnvelope())
491
                            )
492
                        ).toString()
493
                    );
494
                }
495
                FeatureSet set = theStore.getFeatureSet(expression);
496
                final DisposableIterator it = set.fastIterator();
497
                return () -> it;
498
                
499
            } catch(Exception ex) {
500
                return (Iterable<Feature>) IteratorUtils.EMPTY_ITERATOR;
501
            }
502
        }
503
        final Iterator it = index.query(geom);
504
        if( it == null ) {
505
            return (Iterable<Feature>) IteratorUtils.EMPTY_ITERATOR;
506
        }
507
        return () -> new Iterator<Feature>() {
508
            @Override
509
            public boolean hasNext() {
510
                return it.hasNext();
511
            }
512
            
513
            @Override
514
            public Feature next() {
515
                FeatureReference ref = (FeatureReference) it.next();
516
                try {
517
                    return ref.getFeature();
518
                } catch (DataException ex) {
519
                    return null;
520
                }
521
            }
522
        };
523
    }
524

  
525
    @Override
526
    public Feature findFirst(Expression filter) {
527
        try {
528
            return this.getFeatureStore().findFirst(filter);
529
        } catch (Exception ex) {
530
            return null;
531
        }
532
    }
533

  
534
    void setTopologyServices(TopologyServices services) {
535
        this.services = services;
536
        this.restart();
537
    }
538

  
539
}
org.gvsig.topology/tags/org.gvsig.topology-1.0.172/org.gvsig.topology.lib/org.gvsig.topology.lib.impl/src/main/java/org/gvsig/topology/lib/impl/customizablerule/CustomizableRuleActionImpl.java
1
package org.gvsig.topology.lib.impl.customizablerule;
2

  
3
import javax.json.JsonObject;
4
import org.gvsig.expressionevaluator.Expression;
5
import org.gvsig.expressionevaluator.ExpressionUtils;
6
import org.gvsig.expressionevaluator.MutableSymbolTable;
7
import org.gvsig.json.Json;
8
import org.gvsig.json.JsonObjectBuilder;
9
import org.gvsig.json.SupportJson;
10
import org.gvsig.tools.dynobject.DynObject;
11
import org.gvsig.topology.lib.api.ExecuteTopologyRuleActionException;
12
import org.gvsig.topology.lib.api.TopologyReportLine;
13
import org.gvsig.topology.lib.api.TopologyRule;
14
import org.gvsig.topology.lib.spi.AbstractTopologyRuleAction;
15

  
16
/**
17
 *
18
 * @author gvSIG Team
19
 */
20
public class CustomizableRuleActionImpl 
21
        extends AbstractTopologyRuleAction 
22
        implements SupportJson {
23
    
24
    protected Expression action;
25
    protected MutableSymbolTable symbolTable;
26

  
27
    public CustomizableRuleActionImpl() {
28
        super(CustomizableRule0ActionsFactory.NAME);
29
    }
30

  
31
    public Expression getAction() {
32
        return this.action;
33
    }
34

  
35
    public void setAction(Expression action) {
36
        this.action = action;
37
    }
38

  
39
    public void setId(String id) {
40
        this.idAction = id;
41
    }
42

  
43
    public void setName(String name) {
44
        this.name = name;
45
    }
46

  
47
    public void setShortDescription(String description) {
48
        this.shortDescription = description;
49
    }
50

  
51
    public MutableSymbolTable getSymbolTable() {
52
        if (this.symbolTable == null) {
53
            this.symbolTable = ExpressionUtils.createSymbolTable();
54
            this.symbolTable.setVar("action", this);
55
        }
56
        return this.symbolTable;
57
    }
58

  
59
    @Override
60
    public int execute(TopologyRule rule, TopologyReportLine line, DynObject parameters) throws ExecuteTopologyRuleActionException {
61
        MutableSymbolTable st = this.getSymbolTable();
62
        st.setVar("rule", rule);
63
        st.setVar("line", line);
64
        st.setVar("parameters", parameters);
65
        this.action.execute(symbolTable);
66
        return EXECUTE_OK;
67
    }
68

  
69
    @Override
70
    public void fromJson(JsonObject json) {
71
        this.idAction = (String) Json.toObject(json, "idAction");
72
        this.idRule = (String) Json.toObject(json, "idRule");
73
        this.name = (String) Json.toObject(json, "name");
74
        this.shortDescription = (String) Json.toObject(json, "shortDescription");
75
        this.action = (Expression) Json.toObject(json, "expression");
76
    }
77

  
78
    @Override
79
    public JsonObject toJson() {
80
        return toJsonBuilder().build();
81
    }
82

  
83
    @Override
84
    public JsonObjectBuilder toJsonBuilder() {
85
        JsonObjectBuilder builder = Json.createObjectBuilder();
86
        builder.add("idAction", idAction);
87
        builder.add("idRule", idRule);
88
        builder.add("name", name);
89
        builder.add("shortDescription", shortDescription);
90
        builder.add("expression", action);
91
        return builder;
92
    }
93
    
94
}
org.gvsig.topology/tags/org.gvsig.topology-1.0.172/org.gvsig.topology.lib/org.gvsig.topology.lib.impl/src/main/java/org/gvsig/topology/lib/impl/customizablerule/CustomizableRule0ActionsImpl.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2021 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.topology.lib.impl.customizablerule;
25

  
26
import org.apache.commons.lang3.StringUtils;
27
import org.gvsig.expressionevaluator.Expression;
28
import org.gvsig.expressionevaluator.MutableSymbolTable;
29
import org.gvsig.fmap.dal.DALLocator;
30
import org.gvsig.fmap.dal.DataTypeUtils;
31
import org.gvsig.fmap.dal.expressionevaluator.FeatureSymbolTable;
32
import org.gvsig.fmap.dal.feature.Feature;
33
import org.gvsig.tools.ToolsLocator;
34
import org.gvsig.tools.task.SimpleTaskStatus;
35
import org.gvsig.topology.lib.api.TopologyReport;
36
import org.gvsig.topology.lib.api.TopologyRuleFactory;
37
import static org.gvsig.topology.lib.impl.customizablerule.CustomizableRule0ActionsFactory.PARAM_CHECK_NAME;
38
import static org.gvsig.topology.lib.impl.customizablerule.CustomizableRule0ActionsFactory.PARAM_ERRMSG_NAME;
39
import static org.gvsig.topology.lib.impl.customizablerule.CustomizableRule0ActionsFactory.PARAM_NAME_NAME;
40
import org.gvsig.topology.lib.spi.AbstractTopologyRule;
41

  
42
/**
43
 *
44
 * @author gvSIG Team
45
 */
46
@SuppressWarnings("UseSpecificCatch")
47
public class CustomizableRule0ActionsImpl
48
        extends AbstractTopologyRule 
49
    {
50

  
51

  
52
    protected Expression check;
53
    protected String errmsg;
54
    protected FeatureSymbolTable featureSymbolTable;
55
    protected MutableSymbolTable symbolTable;
56

  
57
    public CustomizableRule0ActionsImpl() {
58
        
59
    }
60
            
61
    public CustomizableRule0ActionsImpl(
62
            TopologyRuleFactory factory,
63
            double tolerance,
64
            String dataSet1,
65
            String dataSet2
66
    ) {
67
        super(factory, tolerance, dataSet1, dataSet2);
68
    }
69

  
70
    @Override
71
    public String getName() {
72
        try {
73
            return super.getName()+ "("+(String) this.getParameters().getDynValue(PARAM_NAME_NAME)+")";
74
        } catch(Exception ex) {
75
            return super.getName();
76
        }
77
    }
78

  
79
    @Override
80
    protected void check(SimpleTaskStatus taskStatus, TopologyReport report, Feature feature1) throws Exception {
81
        if (this.symbolTable == null) {
82
            this.featureSymbolTable = DALLocator.getDataManager().createFeatureSymbolTable();
83
            this.symbolTable = this.featureSymbolTable.createParent();
84
            this.symbolTable.setVar("rule", this);
85
        }
86
        if( this.check == null ) {
87
            this.check = (Expression) this.getParameters().getDynValue(PARAM_CHECK_NAME);
88
        }
89
        this.symbolTable.setVar("taskStatus", taskStatus);
90
        this.symbolTable.setVar("report", report);
91
        this.symbolTable.setVar("feature1", feature1);
92
        this.featureSymbolTable.setFeature(feature1);
93
        Object n = this.check.execute(this.featureSymbolTable);
94
        if( DataTypeUtils.isTrue(n, false) ) {
95
            return;
96
        }
97
        report.addLine(
98
                this, 
99
                this.getDataSet1(), 
100
                null, // Dataset2
101
                feature1.getDefaultGeometry(),
102
                null, // Error
103
                feature1.getReference(), 
104
                null, // feature2
105
                false, // is an exception?
106
                getErrorMessage()
107
        );
108
    }
109

  
110
    private String getErrorMessage() {
111
        if( this.errmsg == null ) {
112
            this.errmsg = (String) this.getParameters().getDynValue(PARAM_ERRMSG_NAME);
113
            if( StringUtils.isBlank(this.errmsg) ) {
114
                this.errmsg = ToolsLocator.getI18nManager().getTranslation("_The_verification_expression_was_not_met");
115
            }
116
        }
117
        return this.errmsg;
118
    }
119
}
org.gvsig.topology/tags/org.gvsig.topology-1.0.172/org.gvsig.topology.lib/org.gvsig.topology.lib.impl/src/main/java/org/gvsig/topology/lib/impl/customizablerule/CustomizableRule0ActionsFactory.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2021 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.topology.lib.impl.customizablerule;
25

  
26
import org.gvsig.expressionevaluator.DataTypes;
27
import org.gvsig.json.Json;
28
import org.gvsig.tools.ToolsLocator;
29
import org.gvsig.tools.dynobject.DynField_v2;
30
import org.gvsig.tools.dynobject.DynObject;
31
import org.gvsig.tools.dynobject.DynObjectManager;
32
import org.gvsig.tools.dynobject.DynStruct_v2;
33
import org.gvsig.tools.i18n.I18nManager;
34
import org.gvsig.topology.lib.api.TopologyDataSet;
35
import org.gvsig.topology.lib.api.TopologyLocator;
36
import org.gvsig.topology.lib.api.TopologyManager;
37
import org.gvsig.topology.lib.api.TopologyRule;
38
import org.gvsig.topology.lib.spi.AbstractTopologyRuleFactory;
39

  
40
/**
41
 *
42
 * @author gvSIG Team
43
 */
44
@SuppressWarnings("UseSpecificCatch")
45
public class CustomizableRule0ActionsFactory extends AbstractTopologyRuleFactory {
46
    
47
    public static final String NAME = "Customizable0";
48
    
49
    public static final String PARAM_NAME_NAME = "name";
50
    public static final String PARAM_CHECK_NAME = "check";
51
    public static final String PARAM_ERRMSG_NAME = "errmsg";
52
    
53
    private DynStruct_v2 ruleParametersDefinition;
54
    
55
    public CustomizableRule0ActionsFactory() {
56
        super(
57
                NAME, 
58
                "Customizable0", 
59
                "",
60
                null
61
        );
62
        DynObjectManager dynObjectManager = ToolsLocator.getDynObjectManager();
63
        this.ruleParametersDefinition = (DynStruct_v2) dynObjectManager.get("Topology", "CustomizableRule0Parameters");
64
        if( ruleParametersDefinition==null ) {
65
            ruleParametersDefinition = (DynStruct_v2) dynObjectManager.createDynClass("Topology", "CustomizableRule0Parameters", null);
66
            DynField_v2 param;
67
            param = (DynField_v2) ruleParametersDefinition.addDynFieldString(PARAM_NAME_NAME);
68
            param.setMandatory(true);
69
            param.setLabel("_Name");
70
            param.setDescription("_Name_of_the_rule");
71

  
72
            param = (DynField_v2) ruleParametersDefinition.addDynField(PARAM_CHECK_NAME,DataTypes.EXPRESSION);
73
            param.setMandatory(true);
74
            param.setLabel("_Check_expression");
75
            param.setDescription("_Verification_expression_If_false_the_rule_fails");
76
            
77
            param = (DynField_v2) ruleParametersDefinition.addDynFieldString(PARAM_ERRMSG_NAME);
78
            param.setMandatory(true);
79
            param.setLabel("_Error_message");
80
            param.setDescription("_Message_to_show_if_check_fail");
81
            
82
//            DynField_v2 action = (DynField_v2) ruleParametersDefinition.addDynField("action");
83
//            action.setType(DataTypes.EXPRESSION);
84
        }
85
    }
86

  
87
    @Override
88
    public String getName() {
89
        I18nManager i18n = ToolsLocator.getI18nManager();
90
        return i18n.getTranslation("_Customizable");
91
    }
92

  
93
    @Override
94
    public boolean canApplyToDataSet(TopologyDataSet dataSet) {
95
        return true;
96
    }
97

  
98
    @Override
99
    public boolean canApplyToSecondaryDataSet(TopologyDataSet dataSet) {
100
        return true;
101
    }
102
    
103
    @Override
104
    public TopologyRule createRule(String dataSet1, String dataSet2, double tolerance) {
105
        TopologyRule rule = new CustomizableRule0ActionsImpl(this, tolerance, dataSet1, dataSet2);
106
        return rule;
107
    }    
108

  
109
    @Override
110
    public boolean hasRuleParameters() {
111
        return true;
112
    }
113

  
114
    @Override
115
    public DynObject createRuleParameters() {
116
        DynObjectManager dynObjectManager = ToolsLocator.getDynObjectManager();
117
        DynObject param = dynObjectManager.createDynObject(this.ruleParametersDefinition);
118
        return param;
119
    }
120

  
121
    public static void selfRegister() {
122
        try {
123
            TopologyManager manager = TopologyLocator.getTopologyManager();
124
            manager.addRuleFactories(new CustomizableRule0ActionsFactory());
125
            Json.registerSerializer(CustomizableRule0ActionsImpl.class);
126
        } catch(Exception ex) {
127
            LOGGER.warn("Can't register topology rule from "+CustomizableRule0ActionsFactory.class.getSimpleName(), ex);
128
        }
129
    }
130
}
org.gvsig.topology/tags/org.gvsig.topology-1.0.172/org.gvsig.topology.lib/org.gvsig.topology.lib.impl/src/main/java/org/gvsig/topology/lib/impl/DefaultTopologyManager.java
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.topology.lib.impl;
25

  
26
import java.util.ArrayList;
27
import java.util.Collections;
28
import java.util.HashMap;
29
import java.util.List;
30
import java.util.Map;
31
import org.gvsig.fmap.dal.DataStore;
32
import org.gvsig.topology.lib.api.TopologyDataSet;
33
import org.gvsig.topology.lib.api.TopologyManager;
34
import org.gvsig.topology.lib.api.TopologyPlan;
35
import org.gvsig.topology.lib.api.TopologyRuleFactory;
36
import org.gvsig.topology.lib.api.TopologyServices;
37

  
38
/**
39
 *
40
 * @author jjdelcerro
41
 */
42
public class DefaultTopologyManager implements TopologyManager {
43

  
44
    private final Map<String,TopologyRuleFactory> factories;
45
    private TopologyServices services;
46
    
47
    public DefaultTopologyManager() {
48
        this.factories = new HashMap<>();
49
    }
50
    
51
    @Override
52
    public TopologyPlan createTopologyPlan() {
53
        TopologyPlan plan = new DefaultTopologyPlan(this, this.services);
54
        return plan;
55
    }
56

  
57
    @Override
58
    public List<TopologyRuleFactory> getRuleFactories() {
59
        List<TopologyRuleFactory> l = new ArrayList<>(this.factories.values());
60
        return Collections.unmodifiableList(l);
61
    }
62

  
63
    @Override
64
    public List<TopologyRuleFactory> getRuleFactories(TopologyDataSet dataSet) {
65
        List<TopologyRuleFactory>  f = new ArrayList<>();
66
        for (TopologyRuleFactory factory : this.factories.values()) {
67
            if( factory.canApplyToDataSet(dataSet) ) {
68
                f.add(factory);
69
            }
70
        }
71
        return f;
72
    }
73

  
74
    @Override
75
    public TopologyRuleFactory getRulefactory(String id) {
76
        if( id==null ) {
77
            return null;
78
        }
79
        TopologyRuleFactory factory = this.factories.get(id.toLowerCase());
80
        return factory;
81
    }
82
    
83
    @Override
84
    public void addRuleFactories(TopologyRuleFactory factory) {
85
        if( factory==null ) {
86
            throw new IllegalArgumentException("Invalid null value.");
87
        }
88
        this.factories.put(factory.getId().toLowerCase(), factory);
89
    }
90

  
91
    @Override
92
    public TopologyDataSet createDataSet(String name, DataStore store) {
93
        TopologyDataSet dataSet = new DefaultTopologyDataSet(this.services, name, store);
94
        return dataSet;
95
    }
96
    
97
    @Override
98
    public void setDefaultServices(TopologyServices services) {
99
        this.services = services;
100
    }
101

  
102
    @Override
103
    public TopologyServices getDefaultServices() {
104
        return this.services;
105
    }
106
    
107
}
org.gvsig.topology/tags/org.gvsig.topology-1.0.172/org.gvsig.topology.lib/org.gvsig.topology.lib.impl/src/main/java/org/gvsig/topology/lib/impl/DefaultTopologyPlan.java
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.topology.lib.impl;
25

  
26
import java.util.ArrayList;
27
import java.util.Collection;
28
import java.util.Collections;
29
import java.util.Date;
30
import java.util.HashMap;
31
import java.util.List;
32
import java.util.Map;
33
import javax.json.JsonArray;
34
import javax.json.JsonObject;
35
import javax.json.JsonValue;
36
import org.gvsig.fmap.dal.DataStore;
37
import org.gvsig.fmap.dal.feature.FeatureStore;
38
import org.gvsig.fmap.geom.GeometryLocator;
39
import org.gvsig.fmap.geom.GeometryManager;
40
import org.gvsig.fmap.geom.type.GeometryType;
41
import org.gvsig.json.Json;
42
import org.gvsig.json.JsonArrayBuilder;
43
import org.gvsig.json.JsonObjectBuilder;
44
import org.gvsig.tools.ToolsLocator;
45
import org.gvsig.tools.task.SimpleTaskStatus;
46
import org.gvsig.topology.lib.api.TopologyDataSet;
47
import org.gvsig.topology.lib.api.TopologyManager;
48
import org.gvsig.topology.lib.api.TopologyPlan;
49
import org.gvsig.topology.lib.api.TopologyRule;
50
import org.gvsig.topology.lib.api.TopologyRuleFactory;
51
import org.gvsig.topology.lib.api.TopologyServices;
52
import org.gvsig.topology.lib.spi.AbstractTopologyRule;
53
import org.slf4j.Logger;
54
import org.slf4j.LoggerFactory;
55

  
56
/**
57
 *
58
 * @author jjdelcerro
59
 */
60
@SuppressWarnings("UseSpecificCatch")
61
public class DefaultTopologyPlan implements TopologyPlan {
62

  
63
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultTopologyPlan.class);
64
    
65
    private final TopologyManager manager;
66
    private final Map<String,TopologyDataSet> dataSets;
67
    private final List<TopologyRule> rules;
68

  
69
    private String name;
70
    private DefaultTopologyReport report;
71
    private TopologyServices services;
72
    private double tolerance;
73
    private SimpleTaskStatus taskStatus;
74
    private boolean useUI;
75
    private boolean acceptExceptions;
76
    
77
    public DefaultTopologyPlan(TopologyManager manager, TopologyServices services) {
78
        this.manager = manager;
79
        this.services = services;
80
        this.dataSets = new HashMap<>();
81
        this.rules = new ArrayList<>();
82
        this.report = null;
83
        this.name = "TopologyPlan-" + String.format("%08X", new Date().getTime());
84
        this.tolerance = 0;
85
        this.useUI = true;
86
    }
87

  
88
    @Override
89
    public void setName(String name) {
90
        this.name = name;
91
    }
92

  
93
    @Override
94
    public String getName() {
95
        return this.name;
96
    }
97

  
98
    @Override
99
    public void clear() {
100
        this.name = "";
101
        this.tolerance = 0;
102
        this.services = null;
103
        this.report = null;
104
        this.dataSets.clear();
105
        this.rules.clear();
106
    }
107

  
108
    @Override
109
    public double getTolerance() {
110
        return tolerance;
111
    }
112

  
113
    @Override
114
    public void setTolerance(double tolerance) {
115
        this.tolerance = tolerance;
116
    }
117

  
118
    @Override
119
    public void setTopologyServices(TopologyServices services) {
120
        this.services = services;
121
        for (TopologyDataSet dataSet : this.dataSets.values()) {
122
            if(dataSet instanceof DefaultTopologyDataSet){
123
                ((DefaultTopologyDataSet)dataSet).setTopologyServices(services);
124
            }
125
        }
126
    }
127
    
128
    @Override
129
    public TopologyServices getTopologyServices() {
130
        return this.services;
131
    }
132
    
133
    @Override
134
    public SimpleTaskStatus getTaskStatus() {
135
        if( this.taskStatus == null ) {
136
            this.taskStatus = ToolsLocator.getTaskStatusManager()
137
                    .createDefaultSimpleTaskStatus(this.getName());
138
        }
139
        return this.taskStatus;
140
    }
141
    
142
    @Override
143
    public void execute() {
144
        SimpleTaskStatus theTaskStatus = this.getTaskStatus();
145
        try {
146
            theTaskStatus.restart();
147
            theTaskStatus.message("Preparing the execution of the plan");
148
            theTaskStatus.setAutoremove(true);
149
            theTaskStatus.setIndeterminate();
150
            for (TopologyDataSet dataSet : this.dataSets.values()) {
151
                dataSet.restart();
152
            }
153
            this.getReport().removeAllLines();
154
            long steps = 0;
155
            for (TopologyRule rule : this.rules) {
156
                steps += rule.getSteps();
157
                steps++;
158
            }
159

  
160
            theTaskStatus.setRangeOfValues(0, steps);
161
            theTaskStatus.setCurValue(0);
162
            for (TopologyRule rule : this.rules) {
163
                if( theTaskStatus.isCancellationRequested() ) {
164
                    theTaskStatus.cancel();
165
                    break;
166
                }
167
                theTaskStatus.message(rule.getName());
168
                rule.execute(theTaskStatus, this.getReport());
169
                theTaskStatus.incrementCurrentValue();
170
            }
171
        } catch(Exception ex) {
172
            LOGGER.warn("Problems executing topology plan '"+this.getName()+"'.", ex);
173
            theTaskStatus.abort();
174
        } finally {
175
            if( theTaskStatus.isRunning() ) {
176
                theTaskStatus.terminate();
177
            }
178
            this.getReport().setCompleted(true);
179
        }
180
    }
181

  
182
    @Override
183
    public TopologyDataSet addDataSet(String name, DataStore store) {
184
        TopologyDataSet dataSet = manager.createDataSet(name, store);
185
        return this.addDataSet(dataSet);
186
    }
187

  
188
    @Override
189
    public TopologyDataSet addDataSet(TopologyDataSet dataSet) {
190
        if( this.dataSets.containsKey(dataSet.getName()) ) {
191
            throw new IllegalArgumentException("Already exists a dataSet with this name ("+dataSet.getName()+").");
192
        }
193
        this.dataSets.put(dataSet.getName(), dataSet);
194
        return dataSet;
195
    }
196

  
197
    @Override
198
    public TopologyDataSet getDataSet(String name) {
199
        return this.dataSets.get(name);
200
    }
201

  
202
    @Override
203
    public boolean containsDataSet(String name) {
204
        return this.dataSets.containsKey(name);
205
    }
206

  
207
    @Override
208
    public Collection<TopologyDataSet> getDataSets() {
209
        Collection<TopologyDataSet> x = dataSets.values();
210
        return Collections.unmodifiableCollection(x);
211
    }
212

  
213
    @Override
214
    public Collection<TopologyDataSet> getSecondaryDataSets(TopologyRuleFactory ruleFactory) {
215
        List<TopologyDataSet> secondaryDataSets = new ArrayList<>();
216
        for (TopologyDataSet dataSet : dataSets.values()) {
217
            if( ruleFactory.canApplyToSecondaryDataSet(dataSet) ) {
218
                secondaryDataSets.add(dataSet);
219
            }
220
        }
221
        return secondaryDataSets;
222
    }
223
    
224
    @Override
225
    public TopologyRule addRule(String id, String dataSet1, String dataSet2, double tolerance) {
226
        TopologyRuleFactory factory = this.manager.getRulefactory(id);
227
        if( factory == null ) {
228
            throw new IllegalArgumentException("Can't locate factory for rule '"+id+"'.");
229
        }
230
        if( ! this.canApplyRule(factory, dataSet1, dataSet2) ) {
231
            throw new IllegalArgumentException(
232
                    "Can't apply rule '"+factory.getName()+"' to the datasets '"+dataSet1+"/"+dataSet2+"'."
233
            );
234
        }
235
        TopologyRule rule = factory.createRule(dataSet1, dataSet2, tolerance);
236
        return this.addRule(rule);
237
    }
238

  
239
    @Override
240
    public TopologyRule addRule(TopologyRule rule) {
241
        if( rule.getPlan()!=null && rule.getPlan()!=this ) {
242
            rule = (AbstractTopologyRule) org.gvsig.tools.lang.Cloneable.cloneQuietly(rule);
243
        }
244
        ((AbstractTopologyRule)rule).setPlan(this);
245
        this.rules.add(rule);
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff