Revision 43215 trunk/org.gvsig.desktop/org.gvsig.desktop.plugin/org.gvsig.daltransform.app/org.gvsig.daltransform.app.eventtheme/src/main/java/org/gvsig/app/eventtheme/dal/feature/EventThemeTransform.java

View differences:

EventThemeTransform.java
25 25
 * AUTHORS (In addition to CIT):
26 26
 * 2009 {Iver T.I.}   {Task}
27 27
 */
28

  
29 28
package org.gvsig.app.eventtheme.dal.feature;
30 29

  
31 30
import java.util.Arrays;
32 31

  
33 32
import javax.swing.JOptionPane;
33
import org.apache.commons.lang3.StringUtils;
34 34

  
35 35
import org.cresques.cts.IProjection;
36 36

  
......
74 74
import org.slf4j.LoggerFactory;
75 75

  
76 76
/**
77
 * This class implements a transformation for a events theme. The original 
78
 * {@link DataStore} have to have a couple of attributes, one with the X 
79
 * coordinate and the second one with the Y coordinate. The result of 
80
 * the transformation is a {@link DataStore} that has a new geometric 
81
 * attribute and its value is a point with the coordinates specified in 
82
 * the original {@link DataStore}. 
77
 * This class implements a transformation for a events theme. The original
78
 * {@link DataStore} have to have a couple of attributes, one with the X
79
 * coordinate and the second one with the Y coordinate. The result of the
80
 * transformation is a {@link DataStore} that has a new geometric attribute and
81
 * its value is a point with the coordinates specified in the original
82
 * {@link DataStore}.
83
 *
83 84
 * @author <a href="mailto:jpiera@gvsig.org">Jorge Piera</a>
84 85
 */
85
public class EventThemeTransform extends AbstractFeatureStoreTransform {
86
public class EventThemeTransform
87
    extends AbstractFeatureStoreTransform {
86 88

  
87
	private static Logger logger = LoggerFactory.getLogger(
88
			EventThemeTransform.class);
89
	
89
    private static Logger logger = LoggerFactory.getLogger(
90
        EventThemeTransform.class);
91

  
90 92
    public static final String PERSISTENCE_DEFINITION_NAME = "EventThemeTransform";
91 93
    /**
92
     * Max number of features used for initial estimation
93
     * of extent. Many other features will be ignored
94
     * simply with "iter.next()"
94
     * Max number of features used for initial estimation of extent. Many other
95
     * features will be ignored simply with "iter.next()"
95 96
     */
96 97
    public static int MAX_INI_FEATURES = 200;
97 98

  
......
100 101
    private String geometryFieldName = null;
101 102
    private IProjection projection = null;
102 103
    private FeatureType originalFeatureType;
103
    private GeometryManager geometryManager = GeometryLocator.getGeometryManager();    
104
    private GeometryManager geometryManager = GeometryLocator.getGeometryManager();
104 105
    private Envelope envelope;
105 106

  
106 107
    public EventThemeTransform() {
......
109 110
    }
110 111

  
111 112
    /**
112
     * This method initializes the transformation, sets the name of the parameters and 
113
     * sets the value of the {@link FeatureType} returned by the transformation. 
114
     * @param store
115
     * The original store. 
116
     * @param geometryFieldName
117
     * The field that contains the geometric attribute.
118
     * @param xFieldName
119
     * The field that contains the X coordinate.
120
     * @param yFieldName
121
     * The field that contains the Y coordinate.
113
     * This method initializes the transformation, sets the name of the
114
     * parameters and sets the value of the {@link FeatureType} returned by the
115
     * transformation.
116
     *
117
     * @param store The original store.
118
     * @param geometryFieldName The field that contains the geometric attribute.
119
     * @param xFieldName The field that contains the X coordinate.
120
     * @param yFieldName The field that contains the Y coordinate.
121
     * @param projection
122 122
     * @throws DataException
123 123
     */
124
    public void initialize(
125
    		FeatureStore store,
126
    		String geometryFieldName,
127
    		String xFieldName,
128
    		String yFieldName,
129
    		IProjection projection) throws DataException{
130
    	
124
    public void setValues(
125
        FeatureStore store,
126
        String geometryFieldName,
127
        String xFieldName,
128
        String yFieldName,
129
        IProjection projection) throws DataException {
130

  
131 131
        setFeatureStore(store);
132 132
        this.xFieldName = xFieldName;
133 133
        this.yFieldName = yFieldName;
134 134
        this.projection = projection;
135
        if ((geometryFieldName == null) || (geometryFieldName.equals(""))){
135
        if( StringUtils.isEmpty(geometryFieldName) ) {
136 136
            this.geometryFieldName = "the_geom";
137
        }else{
137
        } else {
138 138
            this.geometryFieldName = geometryFieldName;
139 139
        }
140
    }
141

  
142
    @Override
143
    public void setUp() throws Exception {
144

  
140 145
        this.originalFeatureType = this.getFeatureStore()
141
        .getDefaultFeatureType();
146
            .getDefaultFeatureType();
142 147

  
143 148
        EditableFeatureType type = originalFeatureType.getEditable();
144
        if (type.get(this.geometryFieldName) == null){
145
            EditableFeatureAttributeDescriptor attributeDescriptor = type.add(this.geometryFieldName,  DataTypes.GEOMETRY);
149
        if( type.get(this.geometryFieldName) == null ) {
150
            EditableFeatureAttributeDescriptor attributeDescriptor = type.add(this.geometryFieldName, DataTypes.GEOMETRY);
146 151
            try {
147 152
                attributeDescriptor.setGeometryType(geometryManager.getGeometryType(TYPES.POINT, SUBTYPES.GEOM2D));
148 153
            } catch (GeometryTypeNotSupportedException e) {
149 154
                throw new InitializeException(e);
150 155
            } catch (GeometryTypeNotValidException e) {
151 156
                throw new InitializeException(e);
152
            }           
157
            }
153 158
            attributeDescriptor.setSRS(projection);
154 159
        }
155 160

  
......
157 162
            /*
158 163
             * creates and updates envelope with all features
159 164
             */
160
            initEnvelope(store, MAX_INI_FEATURES);
165
            initEnvelope(this.getFeatureStore(), MAX_INI_FEATURES);
161 166
        } catch (CreateEnvelopeException e) {
162 167
            throw new org.gvsig.fmap.dal.feature.exception.CreateGeometryException(e);
163 168
        }
164 169

  
165 170
        type.setDefaultGeometryAttributeName(this.geometryFieldName);
166
        FeatureType[] types = new FeatureType[] { type.getNotEditableCopy() };
171
        FeatureType[] types = new FeatureType[]{type.getNotEditableCopy()};
167 172
        setFeatureTypes(Arrays.asList(types), types[0]);
168 173
    }
169
    
170
    
171 174

  
172 175
    /**
173 176
     * creates and updates envelope with all features
174
     * 
177
     *
175 178
     */
176 179
    private void initEnvelope(FeatureStore fsto, int max_feats) throws CreateEnvelopeException {
177
        
180

  
178 181
        envelope = geometryManager.createEnvelope(SUBTYPES.GEOM2D);
179 182
        FeatureSet fset = null;
180 183
        DisposableIterator diter = null;
......
182 185
        try {
183 186
            fset = fsto.getFeatureSet();
184 187
            diter = fset.fastIterator();
185
            
188

  
186 189
            // int count = 0;
187 190
            int countused = 0;
188 191
            int nextwait = 1;
189 192
            int index = 0;
190
            
191
            while (diter.hasNext() && (countused < max_feats)) {
192
            	
193

  
194
            while( diter.hasNext() && (countused < max_feats) ) {
195

  
193 196
                feat = (Feature) diter.next();
194 197
                /*
195 198
                 * This loop will use about 70 features from the first
......
206 209
                 * so it's not very important.
207 210
                 */
208 211
                index++;
209
                if (index == nextwait) {
210
                	index = 0;
211
                	/*
212
                if( index == nextwait ) {
213
                    index = 0;
214
                    /*
212 215
                	 * This causes that the first 5 features
213 216
                	 * will always be used.
214
                	 */
215
                	if (countused > 5) {
216
                    	nextwait++;
217
                	}
218
                	this.updateEnvelope(feat);
219
                	countused++;
217
                     */
218
                    if( countused > 5 ) {
219
                        nextwait++;
220
                    }
221
                    this.updateEnvelope(feat);
222
                    countused++;
220 223
                }
221 224
                // count++;
222 225
            }
223
            
226

  
224 227
            diter.dispose();
225
            
228

  
226 229
        } catch (Exception dex) {
227 230
            throw new CreateEnvelopeException(SUBTYPES.GEOM2D, dex);
228 231
        }
229 232
    }
230
    
233

  
231 234
    public void setEnvelope(Envelope env) {
232
    	this.envelope = env;
235
        this.envelope = env;
233 236
    }
234 237

  
235 238
    /*
236 239
     * Currently not used
237 240
     */
238 241
    private void launchFullExtentThread(DisposableIterator diter) {
239
    	
240
    	ComputeExtentTask task = new ComputeExtentTask(diter, this);
241
    	task.start();
242
	}
243 242

  
244
	/* (non-Javadoc)
245
     * @see org.gvsig.fmap.dal.feature.FeatureStoreTransform#applyTransform(org.gvsig.fmap.dal.feature.Feature, org.gvsig.fmap.dal.feature.EditableFeature)
246
     */
243
        ComputeExtentTask task = new ComputeExtentTask(diter, this);
244
        task.start();
245
    }
246

  
247
    @Override
247 248
    public void applyTransform(Feature source, EditableFeature target)
248
    throws DataException {
249
        
249
        throws DataException {
250

  
250 251
        this.copySourceToTarget(source, target);
251 252

  
252 253
        try {
253
            
254
            Geometry point = null;
254

  
255
            Geometry point;
255 256
            Object xval = source.get(xFieldName);
256 257
            Object yval = source.get(yFieldName);
257
            if (xval == null || yval == null) {
258
            if( xval == null || yval == null ) {
258 259
                logger.info("Found row with null coordinates in event theme (created null geometry)");
259 260
                target.set(geometryFieldName, null);
260
                target.setDefaultGeometry(null);  
261
                target.setDefaultGeometry(null);
261 262
            } else {
262 263
                point = geometryManager.createPoint(
263 264
                    new Double(xval.toString()),
264 265
                    new Double(yval.toString()),
265 266
                    SUBTYPES.GEOM2D);
266 267
                target.set(geometryFieldName, point);
267
                target.setDefaultGeometry(point);   
268
                target.setDefaultGeometry(point);
268 269
                envelope.add(point.getEnvelope());
269 270
            }
270
        } catch ( SetReadOnlyAttributeException e1) {            
271
        } catch (SetReadOnlyAttributeException e1) {
271 272
            // Do nothing
272
            
273

  
273 274
        } catch (Exception e) {
274 275
            throw new org.gvsig.fmap.dal.feature.exception.CreateGeometryException(
275 276
                TYPES.POINT, SUBTYPES.GEOM2D, e);
276
        }       
277
        
277
        }
278

  
278 279
    }
279
    
280

  
280 281
    /**
281 282
     * Used internally to initialize envelope
282
     * 
283
     *
283 284
     */
284 285
    private void updateEnvelope(Feature feat) throws CreateGeometryException {
285 286

  
......
299 300
        FeatureType ftSrc = source.getType();
300 301
        FeatureType ftTrg = target.getType();
301 302

  
302

  
303
        for (int i = 0; i < source.getType().size(); i++) {
303
        for( int i = 0; i < source.getType().size(); i++ ) {
304 304
            attr = ftSrc.getAttributeDescriptor(i);
305
            if (ftTrg.getIndex(attr.getName()) > -1) {
305
            if( ftTrg.getIndex(attr.getName()) > -1 ) {
306 306
                try {
307 307
                    target.set(attr.getName(), source.get(i));
308 308
                } catch (IllegalArgumentException e) {
......
315 315

  
316 316
    }
317 317

  
318
    /* (non-Javadoc)
319
     * @see org.gvsig.fmap.dal.feature.FeatureStoreTransform#getSourceFeatureTypeFrom(org.gvsig.fmap.dal.feature.FeatureType)
320
     */
318
    @Override
321 319
    public FeatureType getSourceFeatureTypeFrom(FeatureType targetFeatureType) {
322 320
        return this.originalFeatureType;
323 321
    }
324 322

  
325
    /* (non-Javadoc)
326
     * @see org.gvsig.fmap.dal.feature.FeatureStoreTransform#isTransformsOriginalValues()
327
     */
323
    @Override
328 324
    public boolean isTransformsOriginalValues() {
329 325
        return true;
330 326
    }
......
338 334

  
339 335
        DynStruct definition = persistenceManager.getDefinition(PERSISTENCE_DEFINITION_NAME);
340 336

  
341
        if (definition == null){           
337
        if( definition == null ) {
342 338
            definition = persistenceManager.addDefinition(
343 339
                EventThemeTransform.class,
344 340
                PERSISTENCE_DEFINITION_NAME,
345 341
                "EventThemeTransform Persistence definition",
346
                null, 
342
                null,
347 343
                null
348 344
            );
349 345
            definition.extend(PersistenceManager.PERSISTENCE_NAMESPACE,
......
356 352
        }
357 353
    }
358 354

  
359
    /* (non-Javadoc)
360
     * @see org.gvsig.tools.persistence.Persistent#saveToState(org.gvsig.tools.persistence.PersistentState)
361
     */
355
    @Override
362 356
    public void saveToState(PersistentState state) throws PersistenceException {
363 357
        super.saveToState(state);
364 358
        state.set("geometryFieldName", this.geometryFieldName);
365 359
        state.set("xFieldName", this.xFieldName);
366 360
        state.set("yFieldName", this.yFieldName);
367
        state.set("projection", this.projection);		
361
        state.set("projection", this.projection);
368 362
    }
369 363

  
370
    /* (non-Javadoc)
371
     * @see org.gvsig.tools.persistence.Persistent#loadFromState(org.gvsig.tools.persistence.PersistentState)
372
     */
364
    @Override
373 365
    public void loadFromState(PersistentState state)
374
    throws PersistenceException {
375
        super.loadFromState(state);		
376
        String geometryFieldName = state.getString("geometryFieldName");
377
        String xFieldName = state.getString("xFieldName");
378
        String yFieldName = state.getString("yFieldName");
379
        IProjection projection =  (IProjection)state.get("projection");	
380
        try {
381
            initialize(getFeatureStore(), geometryFieldName, xFieldName, yFieldName, projection);
382
        } catch (DataException e) {
383
            throw new PersistenceException("Impossible to create the transform", e);
384
        }
366
        throws PersistenceException {
367
        super.loadFromState(state);
368
        geometryFieldName = state.getString("geometryFieldName");
369
        xFieldName = state.getString("xFieldName");
370
        yFieldName = state.getString("yFieldName");
371
        projection = (IProjection) state.get("projection");
385 372
    }
386 373

  
374
    @Override
387 375
    public Object getDynValue(String name) throws DynFieldNotFoundException {
388
        if (DataStore.METADATA_CRS.equals(name)){
376
        if( DataStore.METADATA_CRS.equals(name) ) {
389 377
            return projection;
390
        }else if(DataStore.METADATA_ENVELOPE.equals(name)){
378
        } else if( DataStore.METADATA_ENVELOPE.equals(name) ) {
391 379
            return envelope;
392 380
        }
393 381
        return null;
394 382
    }
395 383

  
384
    @Override
396 385
    public boolean hasDynValue(String name) {
397
        return ((DataStore.METADATA_CRS.equals(name)) || 
398
            (DataStore.METADATA_ENVELOPE.equals(name)));
399
    }    
400
    
401
    
386
        return ((DataStore.METADATA_CRS.equals(name))
387
            || (DataStore.METADATA_ENVELOPE.equals(name)));
388
    }
389

  
402 390
    /**
403
     * 
391
     *
404 392
     * A thread to compute the true extent (in case it has a lot of features)
405 393
     * Currently not used.
406
     * 
394
     *
407 395
     * @author jldominguez
408
     * 
396
     *
409 397
     * @deprecated This is not used because it causes issues with
410
     * ConsurrentModificationException because the store is notified of
411
     * a change (the transformation). Anyway, this is not very important I think.
398
     * ConsurrentModificationException because the store is notified of a change
399
     * (the transformation). Anyway, this is not very important I think.
412 400
     */
413
    private class ComputeExtentTask extends AbstractMonitorableTask {
414
    	
415
    	private DisposableIterator disp_iter = null;
416
    	private EventThemeTransform tra_toupdate = null;
417
    	
418
    	public ComputeExtentTask(DisposableIterator diter, EventThemeTransform ettra) {
419
    		/*
401
    private class ComputeExtentTask
402
        extends AbstractMonitorableTask {
403

  
404
        private DisposableIterator disp_iter = null;
405
        private EventThemeTransform tra_toupdate = null;
406

  
407
        public ComputeExtentTask(DisposableIterator diter, EventThemeTransform ettra) {
408
            /*
420 409
    		 * Auto-added by task manager
421
    		 */
422
    		super(Messages.getText("_Extent_of_event_theme"), true);
423
    		disp_iter = diter;
424
    		tra_toupdate = ettra;
425
    	}
426
    	
427
    	public void run() {
410
             */
411
            super(Messages.getText("_Extent_of_event_theme"), true);
412
            disp_iter = diter;
413
            tra_toupdate = ettra;
414
        }
428 415

  
429
    		Envelope env = null;
430
    		Feature feat = null;
431
    		Point point = null;
432
    		int count = 99;
433
    		
434
    		try {
435
                while (disp_iter.hasNext()) {
416
        public void run() {
417

  
418
            Envelope env = null;
419
            Feature feat = null;
420
            Point point = null;
421
            int count = 99;
422

  
423
            try {
424
                while( disp_iter.hasNext() ) {
436 425
                    feat = (Feature) disp_iter.next();
437 426
                    point = geometryManager.createPoint(
438
                            Double.parseDouble(feat.get(xFieldName).toString()),
439
                            Double.parseDouble(feat.get(yFieldName).toString()),
440
                            SUBTYPES.GEOM2D);
441
                    if (env == null) {
442
                    	env = (Envelope) point.getEnvelope().clone();
427
                        Double.parseDouble(feat.get(xFieldName).toString()),
428
                        Double.parseDouble(feat.get(yFieldName).toString()),
429
                        SUBTYPES.GEOM2D);
430
                    if( env == null ) {
431
                        env = (Envelope) point.getEnvelope().clone();
443 432
                    } else {
444
                    	env.add(point.getEnvelope());
433
                        env.add(point.getEnvelope());
445 434
                    }
446 435
                    count++;
447 436
                    Thread.sleep(10);
448
                    if (count % 100 == 0) {
449
                    	System.out.println("COUNT = " + count);
437
                    if( count % 100 == 0 ) {
438
                        System.out.println("COUNT = " + count);
450 439
                    }
451 440
                }
452
    		} catch (Exception exc) {
453
    			
454
    			ApplicationLocator.getManager().message(
455
    					Messages.getText("_Error_while_getting_extent"),
456
    					JOptionPane.ERROR_MESSAGE);
457
    			logger.info("Error while getting extent in thread.", exc);
458
    			
459
    		}
460
    		
461
    		disp_iter.dispose();
462
    		// =================
463
    		if (env != null) {
464
    			Envelope curr_env = (Envelope) tra_toupdate.getDynValue(
465
    					DataStore.METADATA_ENVELOPE); 
466
    			curr_env.add(env);
467
    		}
468
    		// =========== End
469
    		TaskStatusManager man = this.getTaskStatus().getManager();
470
    		man.remove(this.getTaskStatus());
471
    	}
472
    	
441
            } catch (Exception exc) {
442

  
443
                ApplicationLocator.getManager().message(
444
                    Messages.getText("_Error_while_getting_extent"),
445
                    JOptionPane.ERROR_MESSAGE);
446
                logger.info("Error while getting extent in thread.", exc);
447

  
448
            }
449

  
450
            disp_iter.dispose();
451
            // =================
452
            if( env != null ) {
453
                Envelope curr_env = (Envelope) tra_toupdate.getDynValue(
454
                    DataStore.METADATA_ENVELOPE);
455
                curr_env.add(env);
456
            }
457
            // =========== End
458
            TaskStatusManager man = this.getTaskStatus().getManager();
459
            man.remove(this.getTaskStatus());
460
        }
461

  
473 462
    }
474 463
}
475

  

Also available in: Unified diff