Statistics
| Revision:

root / trunk / libraries / libFMap / src-test / com / iver / cit / gvsig / fmap / featureiterators / FeatureIteratorTest.java @ 11971

History | View | Annotate | Download (16.4 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 11971 2007-06-04 07:12:14Z caballero $
47
* $Log$
48
* Revision 1.6  2007-06-04 07:12:14  caballero
49
* connections refactoring
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.ConnectionFactory;
96
import com.iver.cit.gvsig.fmap.drivers.ConnectionJDBC;
97
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
98
import com.iver.cit.gvsig.fmap.drivers.IConnection;
99
import com.iver.cit.gvsig.fmap.drivers.IFeatureIterator;
100
import com.iver.cit.gvsig.fmap.drivers.IVectorialJDBCDriver;
101
import com.iver.cit.gvsig.fmap.layers.FLayer;
102
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
103
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
104
import com.iver.cit.gvsig.fmap.layers.ReadableVectorial;
105
import com.iver.utiles.swing.threads.Cancellable;
106
import com.vividsolutions.jts.geom.Geometry;
107
import com.vividsolutions.jts.geom.GeometryFactory;
108
import com.vividsolutions.jts.io.*;
109

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

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

    
118
        //TODO MOVER TODO LO ESTATICO A UNA CLASE AUXILIAR QUE NO SEA JUNIT
119
        static IProjection PROJECTION_DEFAULT =
120
                CRSFactory.getCRS("EPSG:23030");
121
        static IProjection newProjection =
122
                CRSFactory.getCRS("EPSG:23029");
123

    
124
        static{
125
                try {
126
                        doSetup();
127
                } catch (Exception e) {
128
                        // TODO Auto-generated catch block
129
                        e.printStackTrace();
130
                }
131
        }
132

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

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

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

    
146
                LayerFactory.setDriversPath(baseDriversPath.getAbsolutePath());
147
                if (LayerFactory.getDM().getDriverNames().length < 1)
148
                        throw new Exception("Can't find drivers in path: " + fwAndamiDriverPath);
149
        }
150

    
151

    
152
        protected void setUp() throws Exception {
153
                super.setUp();
154
                doSetup();
155

    
156
        }
157

    
158

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

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

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

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

    
216
        }
217

    
218

    
219
        //test para chequear la rapidez de los metodos de verificacion de candidatos en consultas
220
        //a partir de rectangulo
221
        public void test0(){
222
                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)))";
223
                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)))";
224
                WKTReader reader = new WKTReader(new GeometryFactory());
225
                try {
226
                        Geometry geo1 = reader.read(pol1);
227
                        Geometry geo2 = reader.read(pol2);
228

    
229
                        IGeometry igeo1 = FConverter.jts_to_igeometry(geo1);
230
                        IGeometry igeo2 = FConverter.jts_to_igeometry(geo2);
231

    
232
                        double xmin = 410000;
233
                        double xmax = 415000;
234
                        double ymin = 4790000;
235
                        double ymax = 4793000;
236
                        Rectangle2D rect = new Rectangle2D.Double(xmin, ymin, (xmax-xmin), (ymax-ymin));
237

    
238
                        //PrecciseSpatialCheck
239
                         long t0 = System.currentTimeMillis();
240
                         int NUM_ITERATIONS = 50000;
241
                         for(int i = 0; i < NUM_ITERATIONS;i++){
242
                                 igeo1.fastIntersects(rect.getMinX(),
243
                                                rect.getMinY(), rect.getWidth(), rect.getHeight());
244
                                 igeo2.fastIntersects(rect.getMinX(),
245
                                                        rect.getMinY(), rect.getWidth(), rect.getHeight());
246
                         }
247
                         long t1 = System.currentTimeMillis();
248
                         System.out.println((t1-t0)+" con precissespatialcheck");
249

    
250
                        //FastSpatialCheck
251
                         Rectangle2D b1 = igeo1.getBounds2D();
252
                         Rectangle2D b2 = igeo2.getBounds2D();
253

    
254

    
255
                         long t2 = System.currentTimeMillis();
256
                         for(int i = 0; i < NUM_ITERATIONS;i++){
257
                                 XRectangle2D.intersectInclusive(rect, b1);
258
                                 XRectangle2D.intersectInclusive(rect, b2);
259
                         }
260
                         long t3 = System.currentTimeMillis();
261
                         System.out.println((t3-t2)+" con fastspatialcheck");
262

    
263
                         assertTrue((t3-t2) < (t1 - t0));
264
                        //Spatial index check
265

    
266
                } catch (ParseException e) {
267
                        // TODO Auto-generated catch block
268
                        e.printStackTrace();
269
                }
270

    
271
        }
272

    
273

    
274

    
275

    
276
        //pruebas de iteracion para shp (vectorialfileadapter) y dxf (vectorialadapter)
277
        public void test1() {
278
                try {
279
                        //pruebas de reproyeccion y seleccion de numero de campos
280
                        FLyrVect lyr = (FLyrVect) newLayer("Cantabria.shp", SHP_DRIVER_NAME);
281
                        lyr.setAvailable(true);
282

    
283
                        //iteration selecting two fields
284
                        IFeatureIterator iterator = lyr.getSource().getFeatureIterator(new String[]{"ID", "AREA"}, null);
285
                        IFeature feature = iterator.next();
286
                        assertTrue(feature != null);
287

    
288
                        //iteration with reprojection
289
                        iterator = lyr.getSource().getFeatureIterator((String[])null, newProjection);
290
                        IFeature feature2 = iterator.next();
291
                        //test of field restriction
292
                        assertTrue(feature.getAttributes().length == 2);
293
                        assertTrue(feature2.getAttributes().length > 2);
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("poly-valencia.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