Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extJDBC / src / com / iver / cit / gvsig / fmap / drivers / jdbc / postgis / testPostGis.java @ 5574

History | View | Annotate | Download (17 KB)

1
/*
2
 * Created on 03-mar-2005
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
package com.iver.cit.gvsig.fmap.drivers.jdbc.postgis;
45

    
46
import java.awt.geom.Rectangle2D;
47
import java.sql.Connection;
48
import java.sql.DriverManager;
49
import java.sql.PreparedStatement;
50
import java.sql.ResultSet;
51
import java.sql.ResultSetMetaData;
52
import java.sql.SQLException;
53
import java.sql.Statement;
54
import java.util.Enumeration;
55

    
56
import org.cresques.cts.IProjection;
57
import org.cresques.cts.ProjectionPool;
58
import org.postgresql.fastpath.Fastpath;
59

    
60
import com.iver.cit.gvsig.fmap.core.ICanReproject;
61
import com.iver.cit.gvsig.fmap.core.IFeature;
62
import com.iver.cit.gvsig.fmap.core.IGeometry;
63
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
64
import com.iver.cit.gvsig.fmap.drivers.IFeatureIterator;
65
import com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver;
66
import com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver;
67
import com.iver.cit.gvsig.fmap.drivers.jdbc.WKBParser;
68
import com.iver.cit.gvsig.fmap.drivers.jdbc.WKBParser2;
69
import com.iver.cit.gvsig.fmap.layers.FLayer;
70
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
71
import com.iver.cit.gvsig.fmap.layers.ISpatialDB;
72
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
73
import com.iver.cit.gvsig.fmap.layers.layerOperations.SingleLayer;
74

    
75

    
76
/**
77
 * @author FJP
78
 *
79
 * TODO To change the template for this generated type comment go to
80
 * Window - Preferences - Java - Code Generation - Code and Comments
81
 */
82
public class testPostGis {
83

    
84
      public static void main(String[] args) 
85
      { 
86
      /*    System.err.println("dburl has the following format:");
87
          System.err.println("jdbc:postgresql://HOST:PORT/DATABASENAME");
88
          System.err.println("tablename is 'jdbc_test' by default.");
89
          System.exit(1); */
90

    
91
          
92
          String dburl = "jdbc:postgresql://localhost/latin1";
93
          String dbuser = "postgres";
94
          String dbpass = "aquilina";
95
    
96
          String dbtable = "vias";
97
          
98
          Connection conn = null; 
99
          System.out.println("Creating JDBC connection...");
100
          try {
101
            Class.forName("org.postgresql.Driver");
102
              Enumeration enumDrivers = DriverManager.getDrivers();
103
              while (enumDrivers.hasMoreElements())
104
              {
105
                  System.out.println("Driver " + enumDrivers.nextElement().toString());
106
              }
107
              conn = DriverManager.getConnection(dburl, dbuser, dbpass);
108
          
109
              conn.setAutoCommit(false);
110
          
111
              long t1 = System.currentTimeMillis();
112
              // test1(conn, dburl, dbuser, dbpass, dbtable);
113
              long t2 = System.currentTimeMillis();          
114
              System.out.println("Tiempo de consulta1:" + (t2 - t1) + " milisegundos");
115
              
116
              FLyrVect lyr = initLayerPostGIS();
117
              t1 = System.currentTimeMillis();
118
              test4(lyr);
119
              t2 = System.currentTimeMillis();
120
    
121
              System.out.println("Tiempo de consulta2:" + (t2 - t1) + " milisegundos");
122
               
123
              conn.close();
124

    
125
          } catch (ClassNotFoundException e) {
126
              // TODO Auto-generated catch block
127
              e.printStackTrace();
128
          } catch (SQLException e) {
129
            // TODO Auto-generated catch block
130
            e.printStackTrace();
131
          }
132
          
133
          
134
      }
135
      private static void test1(Connection conn, String dburl, String dbuser, String dbpass, String dbtable)
136
      {          
137
          try 
138
          { 
139
              // magic trickery to be pgjdbc 7.2 compatible
140
              // This works due to the late binding of data types in most java VMs. As
141
              // this is more a demo source than a real-world app, we can risk this
142
              // problem.
143
              /* if (conn.getClass().getName().equals("org.postgresql.jdbc2.Connection")) {
144
                  ((org.postgresql.Connection) conn).addDataType("geometry", "org.postgis.PGgeometry");
145
                  ((org.postgresql.Connection) conn).addDataType("box3d", "org.postgis.PGbox3d");
146
              } else {
147
                  ((org.postgresql.PGConnection) conn).addDataType("geometry", "org.postgis.PGgeometry");
148
                  ((org.postgresql.PGConnection) conn).addDataType("box3d", "org.postgis.PGbox3d");
149
              } */
150

    
151
              
152

    
153
            /* 
154
            * Create a statement and execute a select query. 
155
            */
156
              // String strSQL = "select AsBinary(the_geom) as geom, nom_provin from " + dbtable;
157
              String strSQL = "select ASBINARY(the_geom) as geom, gid from " + dbtable;
158
              // strSQL = "select ASTEXT(the_geom), nom_provin as geom from " + dbtable;
159
              /* String strSQL = "SELECT gid, rd_3, rd_5, rd_6, rd_10, rd_11, rd_12, rd_13, rd_14,"; 
160
              strSQL = strSQL + " rd_15, rd_16, kilometers, cost, metros, AsText(force_2d(the_geom)) FROM vias"; 
161
              strSQL = strSQL + " WHERE TRUE";
162
              */
163
              // PreparedStatement s = conn.prepareStatement(strSQL);
164
              
165
              Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
166
              // s.execute("begin");
167
              
168
              // Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
169
              // s.setFetchSize(5);
170
              int fetchSize = 150000;
171
            s.execute("declare wkb_cursor binary cursor for " + strSQL);
172
            ResultSet r =   s.executeQuery("fetch forward " + fetchSize + " in wkb_cursor"); 
173
              /// ResultSet r =   s.executeQuery("fetch forward all in wkb_cursor");
174
            
175
            // String strSQL2 = "select AsBinary(the_geom) as geom, nom_provin from " + dbtable;
176
            // PreparedStatement ps = conn.prepareStatement(strSQL2);
177
            // ResultSet r = ps.executeQuery();
178
                        
179
              // ResultSet r = s.executeQuery(strSQL);
180
            WKBParser2 parser2 = new WKBParser2();
181
            WKBParser parser = new WKBParser();
182
            long id=0;
183
            /* for (int i=1; i< 100; i++)
184
            {
185
                r.absolute(i);
186
                System.out.println("Row " + i + ":" + r.getString(2));
187
            }
188
            r.beforeFirst();
189
              for (int i=1; i< 100; i++)
190
              {
191
                  r.absolute(i);
192
                  System.out.println("Row " + i + ":" + r.getString(2));
193
              } */
194
              
195
            while( r.next() ) 
196
            { 
197
              /* 
198
              * Retrieve the geometry as an object then cast it to the geometry type. 
199
              * Print things out. 
200
              */ 
201
                // Object obj = r.getObject(2);
202
                byte[] arrayByte = r.getBytes(1);
203
                
204
                // IGeometry gp = parser.parse(arrayByte);
205
                IGeometry gp2 = parser2.parse(arrayByte);
206
                    
207
                // String strAux = r.getString(2);
208
                // int id = r.getInt(2);
209
                // System.out.println("Fila " + id + ":" + obj.toString());
210
                id++;
211
                // Geometry regeom = PGgeometry.geomFromString(obj.toString());
212
                
213
              // PGgeometry geom = (PGgeometry)obj; 
214
               // int id = r.getInt(2);
215
              // System.out.println("Row " + id + ":" + strAux); 
216
              // System.out.println(geom.toString()); 
217
                // System.out.println("provin=" + r.getString(2));
218
                /* if ((id % fetchSize) == 0)
219
                {
220
                    r =   s.executeQuery("fetch forward " + fetchSize + " in wkb_cursor");
221
                } */
222
                            
223
            }
224
            // s.execute("end");
225
            s.close();
226
            
227
          } 
228
          catch( Exception e ) 
229
          { 
230
            e.printStackTrace(); 
231
          }  
232
        }
233
      private static void test2(Connection conn, String dburl, String dbuser, String dbpass, String dbtable)
234
      {          
235
          try 
236
          { 
237
            /* 
238
            * Create a statement and execute a select query. 
239
            */
240
              String strSQL = "select gid from " + dbtable;
241
              PreparedStatement s = conn.prepareStatement(strSQL);
242
              
243
              // Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
244
              int fetchSize = 5000;
245
              ResultSet r = s.executeQuery(strSQL);
246
              int id=0;
247
              while( r.next() ) 
248
              { 
249
                String strAux = r.getString(1);
250
                id++;
251
                // System.out.println("Row " + id + ":" + strAux); 
252
              } 
253
              s.close();
254
          } 
255
          catch( Exception e ) 
256
          { 
257
            e.printStackTrace(); 
258
          }  
259
        }
260

    
261
      
262
      private static void test3(Connection conn, String dburl, String dbuser, String dbpass, String dbtable)
263
      {          
264
          try 
265
          { 
266
                  Fastpath  fp;
267
                  if (conn.getClass().getName().equals("org.postgresql.jdbc2.Connection")) {
268
                          // ((org.postgresql.Connection) conn).addDataType("geometry", "org.postgis.PGgeometry");
269
                          // ((org.postgresql.Connection) conn).addDataType("box3d", "org.postgis.PGbox3d");
270
                  } else {
271
                          ((org.postgresql.PGConnection) conn).addDataType("geometry", "org.postgis.PGgeometry");
272
                          ((org.postgresql.PGConnection) conn).addDataType("box3d", "org.postgis.PGbox3d");
273
                          fp =  ((org.postgresql.PGConnection) conn).getFastpathAPI();
274
                  } 
275

    
276
              
277

    
278
            /* 
279
            * Create a statement and execute a select query. 
280
            */
281
              String strSQL = "select * from " + dbtable;
282
              // String strSQL = "select ASBINARY(the_geom) as geom from " + dbtable;
283
              // strSQL = "select ASTEXT(the_geom), nom_provin as geom from " + dbtable;
284
              /* String strSQL = "SELECT gid, rd_3, rd_5, rd_6, rd_10, rd_11, rd_12, rd_13, rd_14,"; 
285
              strSQL = strSQL + " rd_15, rd_16, kilometers, cost, metros, AsText(force_2d(the_geom)) FROM vias"; 
286
              strSQL = strSQL + " WHERE TRUE";
287
              */
288
              // PreparedStatement s = conn.prepareStatement(strSQL);
289
              
290
              Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
291
              // s.execute("begin");
292
              
293
              // Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
294
              // s.setFetchSize(5);
295
            /*  int fetchSize = 150000;
296
            s.execute("declare wkb_cursor2 binary cursor for " + strSQL);
297
            ResultSet r =   s.executeQuery("fetch forward " + fetchSize + " in wkb_cursor2"); */
298
            
299
            // String strSQL2 = "select AsBinary(the_geom) as geom, nom_provin from " + dbtable;
300
            // PreparedStatement ps = conn.prepareStatement(strSQL2);
301
            // ResultSet r = ps.executeQuery();
302
                        
303
            ResultSet r = s.executeQuery(strSQL);
304
            WKBParser parser = new WKBParser();
305
            long id=0;
306
            /* FastpathArg args[] = new FastpathArg[2];
307
            args[0] = new FastpathArg(fd);
308
            args[1] = new FastpathArg(len);
309
            return fp.getData("loread", args); */  
310
            while( r.next() ) 
311
            { 
312
              /* 
313
              * Retrieve the geometry as an object then cast it to the geometry type. 
314
              * Print things out. 
315
              */ 
316
                Object obj = r.getObject(9);
317
                // fp.
318
                    // final Shape current = (Shape) r.getObject(1);
319
                // byte[] arrayByte = r.getBytes(1);
320
                // String strAux = r.getString(2);
321
                
322
                id++;
323
                // Geometry regeom = PGgeometry.geomFromString(obj.toString());
324
                
325
              // PGgeometry geom = (PGgeometry)obj; 
326
               // int id = r.getInt(2);
327
              // System.out.println("Row " + id + ":" + strAux); 
328
              // System.out.println(geom.toString()); 
329
                // System.out.println("provin=" + r.getString(2));
330
                /* if ((id % fetchSize) == 0)
331
                {
332
                    r =   s.executeQuery("fetch forward " + fetchSize + " in wkb_cursor");
333
                } */
334
                
335
                            
336
            }
337
            // s.execute("end");
338
            s.close();
339
            
340
          } 
341
          catch( Exception e ) 
342
          { 
343
            e.printStackTrace(); 
344
          }  
345
      }
346
      
347
      private static void test4(FLyrVect lyr)
348
      {
349
            try
350
            {
351
                    ISpatialDB dbAdapter = (ISpatialDB) lyr.getSource();
352
            VectorialDatabaseDriver dbDriver = (VectorialDatabaseDriver) dbAdapter.getDriver();
353
                IFeatureIterator geomIt = dbDriver.getFeatureIterator(lyr.getFullExtent(), "23030");
354
                while (geomIt.hasNext())
355
                {
356
                        IFeature feat = geomIt.next();
357
                        IGeometry geom = feat.getGeometry();
358
                }
359
                  }
360
                  catch(Exception e)
361
                  {
362
                          e.printStackTrace();
363
                  }
364

    
365
      }
366

    
367
        private static FLyrVect initLayerPostGIS()
368
        {
369
        String dbURL = "jdbc:postgresql://localhost:5432/latin1"; // latin1 is the catalog name 
370
        String user = "postgres";
371
        String pwd = "aquilina";
372
        String layerName = "vias";
373
        String tableName = "vias";
374
        Connection conn;
375
        LayerFactory.setDriversPath("D:/eclipse/workspace/_fwAndami/gvSIG/extensiones/com.iver.cit.gvsig/drivers");
376
                try {
377
                        conn = DriverManager.getConnection(dbURL, user, pwd);
378
                conn.setAutoCommit(false);
379
                
380
                String fidField = "gid"; // BE CAREFUL => MAY BE NOT!!!
381
                String geomField = "the_geom"; // BE CAREFUL => MAY BE NOT!!! => You should read table GEOMETRY_COLUMNS.
382
                                                                                // See PostGIS help.
383

    
384
                // To obtain the fields, make a connection and get them. 
385
                        /* Statement st = conn.createStatement();
386
                        ResultSet rs = st.executeQuery("select * from " + tableName + " LIMIT 1");
387
                        ResultSetMetaData rsmd = rs.getMetaData();
388
                        String[] fields = new String[rsmd.getColumnCount()-1]; // We don't want to include the_geom field
389
                        int j = 0;
390
                        for (int i = 0; i < fields.length; i++) {
391
                                if (!rsmd.getColumnName(i+1).equalsIgnoreCase(geomField))
392
                                {
393
                                        fields[j++] = rsmd.getColumnName(i+1);                                        
394
                                }
395
                        }
396
                        rs.close(); */        
397
                
398
                String[] fields = new String[1];                
399
                fields[0] = "gid"; 
400
                
401
                String whereClause = "";
402
        
403
                VectorialJDBCDriver driver = (VectorialJDBCDriver) LayerFactory.getDM()
404
                                        .getDriver("PostGIS JDBC Driver");
405
                
406
                // Here you can set the workingArea
407
                // driver.setWorkingArea(dbLayerDefinition.getWorkingArea());
408
                
409
                
410
                String strEPSG = "23030";
411
                DBLayerDefinition lyrDef = new DBLayerDefinition();                
412
                lyrDef.setName(layerName);
413
                lyrDef.setTableName(tableName);
414
                lyrDef.setWhereClause(whereClause);
415
                lyrDef.setFieldNames(fields);
416
                lyrDef.setFieldGeometry(geomField);
417
                lyrDef.setFieldID(fidField);
418
                // if (dbLayerDefinition.getWorkingArea() != null)
419
                //     lyrDef.setWorkingArea(dbLayerDefinition.getWorkingArea());
420
                
421
                lyrDef.setSRID_EPSG(strEPSG);
422
                if (driver instanceof ICanReproject)
423
                {                    
424
                    ((ICanReproject)driver).setDestProjection(strEPSG);
425
                }
426
                driver.setData(conn, lyrDef);
427
                IProjection proj = null; 
428
                if (driver instanceof ICanReproject)
429
                {                                        
430
                    proj = ProjectionPool.get("EPSG:" + ((ICanReproject)driver).getSourceProjection()); 
431
                }
432
                
433
                FLayer lyr = LayerFactory.createDBLayer(driver, layerName, proj);
434
                Rectangle2D rectAux = lyr.getFullExtent();
435
                return (FLyrVect) lyr;
436
                }
437
                catch(Exception e)
438
                {
439
                        e.printStackTrace();
440
                }
441
                return null;
442
        }
443
}