Statistics
| Revision:

svn-gvsig-desktop / trunk / libraries / libFMap / src-test / com / iver / cit / gvsig / fmap / featureiterators / FeatureIteratorTest.java @ 12052

History | View | Annotate | Download (16.8 KB)

1
/*
2
 * Created on 17-abr-2007
3
 *
4
 * gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
5
 *
6
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
7
 *
8
 * This program is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU General Public License
10
 * as published by the Free Software Foundation; either version 2
11
 * of the License, or (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, write to the Free Software
20
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
21
 *
22
 * For more information, contact:
23
 *
24
 *  Generalitat Valenciana
25
 *   Conselleria d'Infraestructures i Transport
26
 *   Av. Blasco Ib??ez, 50
27
 *   46010 VALENCIA
28
 *   SPAIN
29
 *
30
 *      +34 963862235
31
 *   gvsig@gva.es
32
 *      www.gvsig.gva.es
33
 *
34
 *    or
35
 *
36
 *   IVER T.I. S.A
37
 *   Salamanca 50
38
 *   46005 Valencia
39
 *   Spain
40
 *
41
 *   +34 963163400
42
 *   dac@iver.es
43
 */
44
/* CVS MESSAGES:
45
*
46
* $Id: FeatureIteratorTest.java 12052 2007-06-07 10:20:38Z azabala $
47
* $Log$
48
* Revision 1.8  2007-06-07 10:20:38  azabala
49
* includes closeIterator
50
*
51
* Revision 1.7  2007/06/07 09:31:42  azabala
52
* *** empty log message ***
53
*
54
* Revision 1.5  2007/05/29 19:11:03  azabala
55
* *** empty log message ***
56
*
57
* Revision 1.4  2007/05/23 16:54:29  azabala
58
* new test for bug 2510 phpcollab task (infinite loop for poly-valencia.shp)
59
*
60
* Revision 1.3  2007/05/08 08:48:27  jaume
61
* GRAPHIC TESTING FOR ISYMBOLS!!!
62
*
63
* Revision 1.2  2007/04/25 15:16:10  azabala
64
* tests for featureiterators with mysql database
65
*
66
* Revision 1.1  2007/04/19 18:12:56  azabala
67
* *** empty log message ***
68
*
69
*
70
*/
71
package com.iver.cit.gvsig.fmap.featureiterators;
72

    
73
import java.awt.Dimension;
74
import java.awt.Toolkit;
75
import java.awt.geom.Rectangle2D;
76
import java.awt.image.BufferedImage;
77
import java.io.File;
78
import java.net.URL;
79
import java.sql.Connection;
80
import java.sql.DriverManager;
81
import java.util.prefs.Preferences;
82

    
83
import junit.framework.TestCase;
84

    
85
import org.cresques.cts.IProjection;
86
import org.geotools.resources.geometry.XRectangle2D;
87

    
88
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
89
import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileReadException;
90
import com.iver.cit.gvsig.exceptions.layers.LoadLayerException;
91
import com.iver.cit.gvsig.fmap.MapContext;
92
import com.iver.cit.gvsig.fmap.ViewPort;
93
import com.iver.cit.gvsig.fmap.core.ICanReproject;
94
import com.iver.cit.gvsig.fmap.core.IFeature;
95
import com.iver.cit.gvsig.fmap.core.IGeometry;
96
import com.iver.cit.gvsig.fmap.core.v02.FConverter;
97
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
98
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
99
import com.iver.cit.gvsig.fmap.drivers.DefaultJDBCDriver;
100
import com.iver.cit.gvsig.fmap.drivers.IConnection;
101
import com.iver.cit.gvsig.fmap.drivers.IFeatureIterator;
102
import com.iver.cit.gvsig.fmap.drivers.IVectorialJDBCDriver;
103
import com.iver.cit.gvsig.fmap.layers.FLayer;
104
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
105
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
106
import com.iver.utiles.swing.threads.Cancellable;
107
import com.vividsolutions.jts.geom.Geometry;
108
import com.vividsolutions.jts.geom.GeometryFactory;
109
import com.vividsolutions.jts.io.ParseException;
110
import com.vividsolutions.jts.io.WKTReader;
111

    
112
public class FeatureIteratorTest extends TestCase {
113
        static final String fwAndamiDriverPath = "../_fwAndami/gvSIG/extensiones/com.iver.cit.gvsig/drivers";
114
        private static File baseDataPath;
115
        private static File baseDriversPath;
116

    
117
        public static String SHP_DRIVER_NAME = "gvSIG shp driver";
118
        public  static String DXF_DRIVER_NAME = "gvSIG DXF Memory Driver";
119

    
120
        //TODO MOVER TODO LO ESTATICO A UNA CLASE AUXILIAR QUE NO SEA JUNIT
121
        static IProjection PROJECTION_DEFAULT =
122
                CRSFactory.getCRS("EPSG:23030");
123
        static IProjection newProjection =
124
                CRSFactory.getCRS("EPSG:23029");
125
        
126
        static{
127
                try {
128
                        doSetup();
129
                } catch (Exception e) {
130
                        // TODO Auto-generated catch block
131
                        e.printStackTrace();
132
                }
133
        }
134

    
135
        private static void doSetup() throws Exception{
136
                URL url = FeatureIteratorTest.class.getResource("testdata");
137
                if (url == null)
138
                        throw new Exception("No se encuentra el directorio con datos de prueba");
139

    
140
                baseDataPath = new File(url.getFile());
141
                if (!baseDataPath.exists())
142
                        throw new Exception("No se encuentra el directorio con datos de prueba");
143

    
144
                baseDriversPath = new File(fwAndamiDriverPath);
145
                if (!baseDriversPath.exists())
146
                        throw new Exception("Can't find drivers path: " + fwAndamiDriverPath);
147

    
148
                LayerFactory.setDriversPath(baseDriversPath.getAbsolutePath());
149
                if (LayerFactory.getDM().getDriverNames().length < 1)
150
                        throw new Exception("Can't find drivers in path: " + fwAndamiDriverPath);
151
        }
152
        
153
        
154
        protected void setUp() throws Exception {
155
                super.setUp();
156
                doSetup();
157
                
158
        }
159

    
160

    
161
        public static  FLayer newLayer(String fileName,
162
                                                                           String driverName)
163
                                                                throws LoadLayerException {
164
                File file = new File(baseDataPath, fileName);
165
                return LayerFactory.createLayer(fileName,
166
                                                                                driverName,
167
                                                                                file, PROJECTION_DEFAULT);
168
        }
169

    
170
        public static FLyrVect newJdbcLayer(String layerName) throws LoadLayerException{
171
                String dbURL = "jdbc:mysql://localhost:3306/datos";
172
                String user = "root";
173
                String pwd = "root";
174
                String tableName = layerName;
175
                Connection conn;
176
                try {
177
                                Class.forName("com.mysql.jdbc.Driver");
178
                        } catch (ClassNotFoundException e1) {
179
                                throw new LoadLayerException(layerName, e1);
180
                        }
181
                        try {
182
                                conn = DriverManager.getConnection(dbURL, user, pwd);
183
                        conn.setAutoCommit(false);
184

    
185
                        String fidField = "gid";
186
                        String geomField = "geom";
187
                        String[] fields = new String[1];
188
                        fields[0] = "gid";
189
                        String whereClause = "";
190
                        IVectorialJDBCDriver driver = (IVectorialJDBCDriver)
191
                                LayerFactory.getDM().getDriver("mySQL JDBC Driver");
192
                        String strEPSG = "23030";
193
                        DBLayerDefinition lyrDef = new DBLayerDefinition();
194
                        lyrDef.setName(layerName);
195
                        lyrDef.setTableName(tableName);
196
                        lyrDef.setWhereClause(whereClause);
197
                        lyrDef.setFieldGeometry(geomField);
198
                        lyrDef.setFieldNames(fields);
199
                        lyrDef.setFieldID(fidField);
200
                        lyrDef.setSRID_EPSG(strEPSG);
201
                        if (driver instanceof ICanReproject)
202
                        {
203
                            ((ICanReproject)driver).setDestProjection(strEPSG);
204
                        }
205
                        ((DefaultJDBCDriver)driver).setData((IConnection) conn, lyrDef);
206
                        IProjection proj = null;
207
                        if (driver instanceof ICanReproject)
208
                        {
209
                            proj = CRSFactory.getCRS("EPSG:" + ((ICanReproject)driver).getSourceProjection());
210
                        }
211

    
212
                        return (FLyrVect) LayerFactory.createDBLayer(driver, layerName, proj);
213
                        }catch(Exception e){
214
                                e.printStackTrace();
215
                        }
216
                        return null;
217

    
218
        }
219
        
220
        
221
        //test para chequear la rapidez de los metodos de verificacion de candidatos en consultas
222
        //a partir de rectangulo
223
        public void test0(){
224
                String pol1 = "MULTIPOLYGON (((413434.195990259 4790622.699703139, 413441.7000601477 4790624.699360616, 413442.6978540559 4790620.700045662, 413435.2020303979 4790618.700388186, 413434.195990259 4790622.699703139, 413434.195990259 4790622.699703139)))";
225
                String pol2 = "MULTIPOLYGON (((411585.59723499016 4791781.20126231, 411575.39664767997 4791791.999412685, 411586.29816459515 4791802.297648691, 411596.4987519054 4791791.499498316, 411585.59723499016 4791781.20126231, 411585.59723499016 4791781.20126231)))";
226
                WKTReader reader = new WKTReader(new GeometryFactory());
227
                try {
228
                        Geometry geo1 = reader.read(pol1);
229
                        Geometry geo2 = reader.read(pol2);
230
                        
231
                        IGeometry igeo1 = FConverter.jts_to_igeometry(geo1);
232
                        IGeometry igeo2 = FConverter.jts_to_igeometry(geo2);
233
                        
234
                        double xmin = 410000;
235
                        double xmax = 415000;
236
                        double ymin = 4790000;
237
                        double ymax = 4793000;
238
                        Rectangle2D rect = new Rectangle2D.Double(xmin, ymin, (xmax-xmin), (ymax-ymin));
239
                        
240
                        //PrecciseSpatialCheck
241
                         long t0 = System.currentTimeMillis();
242
                         int NUM_ITERATIONS = 50000;
243
                         for(int i = 0; i < NUM_ITERATIONS;i++){
244
                                 igeo1.fastIntersects(rect.getMinX(),
245
                                                rect.getMinY(), rect.getWidth(), rect.getHeight());
246
                                 igeo2.fastIntersects(rect.getMinX(),
247
                                                        rect.getMinY(), rect.getWidth(), rect.getHeight());
248
                         }         
249
                         long t1 = System.currentTimeMillis();
250
                         System.out.println((t1-t0)+" con precissespatialcheck");
251
                        
252
                        //FastSpatialCheck
253
                         Rectangle2D b1 = igeo1.getBounds2D();
254
                         Rectangle2D b2 = igeo2.getBounds2D();
255
                         
256
                         
257
                         long t2 = System.currentTimeMillis();
258
                         for(int i = 0; i < NUM_ITERATIONS;i++){
259
                                 XRectangle2D.intersectInclusive(rect, b1);
260
                                 XRectangle2D.intersectInclusive(rect, b2);
261
                         }         
262
                         long t3 = System.currentTimeMillis();
263
                         System.out.println((t3-t2)+" con fastspatialcheck");
264
                         
265
                         assertTrue((t3-t2) < (t1 - t0));
266
                        //Spatial index check
267
                        
268
                } catch (ParseException e) {
269
                        // TODO Auto-generated catch block
270
                        e.printStackTrace();
271
                }
272
                
273
        }
274
        
275
        
276
        
277

    
278
        //pruebas de iteracion para shp (vectorialfileadapter) y dxf (vectorialadapter)
279
        public void test1() {
280
                try {
281
                        //pruebas de reproyeccion y seleccion de numero de campos
282
                        FLyrVect lyr = (FLyrVect) newLayer("Cantabria.shp", SHP_DRIVER_NAME);
283
                        lyr.setAvailable(true);
284
                        
285
                        //iteration selecting two fields
286
                        IFeatureIterator iterator = lyr.getSource().getFeatureIterator(new String[]{"ID", "AREA"}, null);
287
                        IFeature feature = iterator.next();
288
                        assertTrue(feature != null);
289

    
290
                        //iteration with reprojection
291
                        iterator = lyr.getSource().getFeatureIterator((String[])null, newProjection);
292
                        IFeature feature2 = iterator.next();
293
                        //test of field restriction
294
                        assertTrue(feature.getAttributes().length == 2);
295
                        //si pasamos null, no devuelve ning?n campo
296
                        assertTrue(feature2.getAttributes().length == 0);
297
                        assertTrue(!feature.getGeometry().toJTSGeometry().equals(feature2.getGeometry().toJTSGeometry()));
298
                        iterator.closeIterator();
299

    
300
                        //pruebas de iteracion espacial
301
                        FLyrVect lyr2 = (FLyrVect) newLayer("Edificaciones.shp", SHP_DRIVER_NAME);
302
                        lyr2.setAvailable(true);
303
                        double xmin = 410000;
304
                        double xmax = 415000;
305
                        double ymin = 4790000;
306
                        double ymax = 4793000;
307
                        Rectangle2D rect = new Rectangle2D.Double(xmin, ymin, (xmax-xmin), (ymax-ymin));
308
                        
309
                        //fast iteration
310
                        long t0 = System.currentTimeMillis();
311
                        iterator = lyr2.getSource().getFeatureIterator(rect, null, newProjection, true);
312
                        int numFeatures = 0;
313
                        while(iterator.hasNext()){
314
                                feature = iterator.next();
315
                                numFeatures++;
316
                        }
317
                        long t1 = System.currentTimeMillis();
318
                
319
                        //vemos si hay diferencia entre el fast = true y el fast = false
320
                        iterator = lyr2.getSource().getFeatureIterator(rect, null, newProjection, false);
321
                        int numFeatures3 = 0;
322
                        while(iterator.hasNext()){
323
                                feature = iterator.next();
324
                                numFeatures3++;
325
                        }
326
                        long t2 = System.currentTimeMillis();
327
                        assertTrue(numFeatures3 <= numFeatures);
328
                        iterator.closeIterator();
329
                        System.out.println((t1-t0)+" en la iteracion rapida");
330
                        System.out.println("Recuperados "+numFeatures);
331
                        System.out.println((t2-t1)+" en la iteracion lenta");
332
                        System.out.println("Recuperados "+numFeatures3);
333
                        
334
                        
335
                        int numFeatures2 = 0;
336
                        iterator = lyr2.getSource().getFeatureIterator();
337
                        while(iterator.hasNext()){
338
                                feature = iterator.next();
339
                                numFeatures2++;
340
                        }
341
                        assertTrue(numFeatures2 > numFeatures);
342
                        iterator.closeIterator();
343

    
344
                        //pruebas de iteracion en base a criterios alfanumericos
345
                        final String expr = "select * from " + lyr.getRecordset().getName() + " where area < 700;";
346
                        iterator = lyr.getSource().getFeatureIterator(expr, null);
347
                        numFeatures2 = 0;
348
                        while(iterator.hasNext()){
349
                                feature = iterator.next();
350
                                numFeatures2++;
351
                        }
352
                        iterator.closeIterator();
353
                        iterator = lyr.getSource().getFeatureIterator();
354
                        while(iterator.hasNext()){
355
                                feature = iterator.next();
356
                                numFeatures++;
357
                        }
358
                        assertTrue(numFeatures2 > 0);
359
                        assertTrue(numFeatures > numFeatures2);
360
                        iterator.closeIterator();
361

    
362
                        //pruebas con el driver dxf en vez del shp
363
                        FLyrVect lyr3 = (FLyrVect) newLayer("es1120003_2_02.dxf", DXF_DRIVER_NAME);
364
                        lyr3.setAvailable(true);
365
                        iterator = lyr3.getSource().getFeatureIterator("select * from "+lyr3.getRecordset().getName()+" where ID > 17;", null);
366
                        numFeatures2 = 0;
367
                        while(iterator.hasNext()){
368
                                feature = iterator.next();
369
                                numFeatures2++;
370
                        }
371
                        iterator.closeIterator();
372
                        assertTrue(numFeatures2 > 0);
373

    
374
                        //queda por probar los iteradores contra base de datos
375
                        //en base a criterios alfanumericos y espaciales
376

    
377
                } catch (LoadLayerException e) {
378
                        // TODO Auto-generated catch block
379
                        e.printStackTrace();
380
                } catch (ReadDriverException e) {
381
                        // TODO Auto-generated catch block
382
                        e.printStackTrace();
383
                } catch (ExpansionFileReadException e) {
384
                        // TODO Auto-generated catch block
385
                        e.printStackTrace();
386
                }
387
        }
388

    
389
        
390
        
391
//        public void test3(){
392
//                try {
393
//                        FLyrVect layer = (FLyrVect) newLayer("poly-valencia.shp", SHP_DRIVER_NAME);
394
//                        IFeatureIterator iterator = layer.getSource().getFeatureIterator();
395
//                        int numFeatures = 0;
396
//                        while(iterator.hasNext()){
397
//                                iterator.next();
398
//                                numFeatures++;
399
//                        }
400
//                        assert(layer.getSource().getShapeCount() == numFeatures);
401
//
402
//                } catch (LoadLayerException e) {
403
//                        // TODO Auto-generated catch block
404
//                        e.printStackTrace();
405
//                } catch (ReadDriverException e) {
406
//                        // TODO Auto-generated catch block
407
//                        e.printStackTrace();
408
//                } catch (ExpansionFileReadException e) {
409
//                        // TODO Auto-generated catch block
410
//                        e.printStackTrace();
411
//                }
412
//
413
//        }
414
        
415
        //test of featureIterator with layer poly-valencia using a spatial filter.
416
        //jaume found a bug with an infinite loop iteration 
417
        
418
        public void test4(){
419
                try {
420
                        FLyrVect layer = (FLyrVect) newLayer("poly-valencia.shp", SHP_DRIVER_NAME);
421
                        Rectangle2D extent = layer.getFullExtent();
422
                        String[] fields = layer.getRecordset().getFieldNames();
423
                        
424
                        
425
                        IFeatureIterator iterator = layer.
426
                                                        getSource().
427
                                                        getFeatureIterator(extent,fields, null, true);
428
                        int numFeatures = 0;
429
                        while(iterator.hasNext()){
430
                                iterator.next();
431
                                numFeatures++;
432
                        }
433
                        iterator.closeIterator();
434
                        assert(layer.getSource().getShapeCount() == numFeatures);
435

    
436
                } catch (LoadLayerException e) {
437
                        // TODO Auto-generated catch block
438
                        e.printStackTrace();
439
                } catch (ReadDriverException e) {
440
                        // TODO Auto-generated catch block
441
                        e.printStackTrace();
442
                } catch (ExpansionFileReadException e) {
443
                        // TODO Auto-generated catch block
444
                        e.printStackTrace();
445
                }
446
        }
447
        
448
        
449
        
450
        
451
        
452
        public void test5(){
453
                        try {
454
                                int WIDTH = 300;
455
                                int HEIGHT = 200;
456
                                FLyrVect layer = (FLyrVect) newLayer("municipios.shp", SHP_DRIVER_NAME);
457
                                ViewPort vp = new ViewPort(PROJECTION_DEFAULT);
458
                                vp.setImageSize(new Dimension(WIDTH, HEIGHT));
459
                                vp.setExtent(layer.getFullExtent());
460
                                MapContext mapa = new MapContext(vp);
461
                                mapa.getLayers().addLayer(layer);
462
                                BufferedImage img = new BufferedImage(WIDTH, HEIGHT,
463
                                                BufferedImage.TYPE_INT_ARGB);
464
                                
465
                                long t0 = System.currentTimeMillis();
466
                                mapa.draw(img, img.createGraphics(),mapa.getScaleView());
467
                                long t1 = System.currentTimeMillis();
468
                                System.out.println((t1-t0)+" en dibujar con MapContext.draw");
469
                                
470
                                
471
                                long t2 = System.currentTimeMillis();
472
                                layer.draw(img, img.createGraphics(),vp, new Cancellable(){
473
                                        public boolean isCanceled() {
474
                                                return false;
475
                                        }
476
                                        public void setCanceled(boolean canceled) {
477
                                        }}, getScaleView(vp));
478
                                long t3 = System.currentTimeMillis();
479
                                System.out.println((t3-t2)+" en dibujar con layer._draw");
480
                                
481
                        } catch (LoadLayerException e) {
482
                                // TODO Auto-generated catch block
483
                                e.printStackTrace();
484
                        } catch (ReadDriverException e) {
485
                                // TODO Auto-generated catch block
486
                                e.printStackTrace();
487
                        } catch (ExpansionFileReadException e) {
488
                                // TODO Auto-generated catch block
489
                                e.printStackTrace();
490
                        }
491
                        
492
        }
493
        
494
        
495
                
496
                
497
        
498
        //TODO Mover spatialindextest a esta clase
499
        public void test7(){
500
                
501
        }
502
        
503
        
504
        private long getScaleView(ViewPort viewPort) {
505
                double[] CHANGE = { 100000, 100, 1, 0.1, 160934.4,
506
                                91.44, 30.48, 2.54, 1/8.983152841195214E-4 };
507
                Preferences prefsResolution = Preferences.userRoot().node( "gvsig.configuration.screen" );
508
                Toolkit kit = Toolkit.getDefaultToolkit();
509
                double dpi = prefsResolution.getInt("dpi",kit.getScreenResolution());
510
                IProjection proj = viewPort.getProjection();
511
                if (viewPort.getImageSize() == null)
512
                        return -1;
513
                if (viewPort.getAdjustedExtent() == null) {
514
                        return 0;
515
                }
516
                if (proj == null) {
517
                        double w = ((viewPort.getImageSize().getWidth() / dpi) * 2.54);
518
                        return (long) (viewPort.getAdjustedExtent().getWidth() / w * CHANGE[viewPort.getMapUnits()]);
519
                }
520

    
521
                return Math.round(proj.getScale(viewPort.getAdjustedExtent().getMinX(),
522
                                viewPort.getAdjustedExtent().getMaxX(), viewPort.getImageSize()
523
                                                .getWidth(), dpi));
524
        }
525
        
526
}
527