Statistics
| Revision:

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

History | View | Annotate | Download (16.5 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 12049 2007-06-07 09:31:42Z azabala $
47
* $Log$
48
* Revision 1.7  2007-06-07 09:31:42  azabala
49
* *** empty log message ***
50
*
51
* Revision 1.5  2007/05/29 19:11:03  azabala
52
* *** empty log message ***
53
*
54
* Revision 1.4  2007/05/23 16:54:29  azabala
55
* new test for bug 2510 phpcollab task (infinite loop for poly-valencia.shp)
56
*
57
* Revision 1.3  2007/05/08 08:48:27  jaume
58
* GRAPHIC TESTING FOR ISYMBOLS!!!
59
*
60
* Revision 1.2  2007/04/25 15:16:10  azabala
61
* tests for featureiterators with mysql database
62
*
63
* Revision 1.1  2007/04/19 18:12:56  azabala
64
* *** empty log message ***
65
*
66
*
67
*/
68
package com.iver.cit.gvsig.fmap.featureiterators;
69

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

    
80
import junit.framework.TestCase;
81

    
82
import org.cresques.cts.IProjection;
83
import org.geotools.resources.geometry.XRectangle2D;
84

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

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

    
114
        public static String SHP_DRIVER_NAME = "gvSIG shp driver";
115
        public  static String DXF_DRIVER_NAME = "gvSIG DXF Memory Driver";
116

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

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

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

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

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

    
157

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

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

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

    
209
                        return (FLyrVect) LayerFactory.createDBLayer(driver, layerName, proj);
210
                        }catch(Exception e){
211
                                e.printStackTrace();
212
                        }
213
                        return null;
214

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

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

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

    
296

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

    
340

    
341
                        //pruebas de iteracion en base a criterios alfanumericos
342
                        final String expr = "select * from " + lyr.getRecordset().getName() + " where area < 700;";
343
                        iterator = lyr.getSource().getFeatureIterator(expr, null);
344
                        numFeatures2 = 0;
345
                        while(iterator.hasNext()){
346
                                feature = iterator.next();
347
                                numFeatures2++;
348
                        }
349

    
350
                        iterator = lyr.getSource().getFeatureIterator();
351
                        while(iterator.hasNext()){
352
                                feature = iterator.next();
353
                                numFeatures++;
354
                        }
355
                        assertTrue(numFeatures2 > 0);
356
                        assertTrue(numFeatures > numFeatures2);
357

    
358

    
359

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

    
371
                        //queda por probar los iteradores contra base de datos
372
                        //en base a criterios alfanumericos y espaciales
373

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

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

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

    
517
                return Math.round(proj.getScale(viewPort.getAdjustedExtent().getMinX(),
518
                                viewPort.getAdjustedExtent().getMaxX(), viewPort.getImageSize()
519
                                                .getWidth(), dpi));
520
        }
521
        
522
}
523