Statistics
| Revision:

svn-gvsig-desktop / tags / v10_RC2c / extensions / extJDBC / src / com / iver / cit / gvsig / fmap / drivers / jdbc / postgis / testPostGis.java @ 8745

History | View | Annotate | Download (19.1 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.nio.ByteBuffer;
48
import java.sql.Connection;
49
import java.sql.Date;
50
import java.sql.DriverManager;
51
import java.sql.PreparedStatement;
52
import java.sql.ResultSet;
53
import java.sql.SQLException;
54
import java.sql.Statement;
55
import java.sql.Time;
56
import java.sql.Timestamp;
57
import java.util.Calendar;
58
import java.util.Enumeration;
59
import java.util.GregorianCalendar;
60

    
61
import javax.swing.UIManager;
62

    
63
import org.cresques.cts.IProjection;
64
import org.cresques.cts.ProjectionPool;
65
import org.postgresql.fastpath.Fastpath;
66

    
67
import com.iver.cit.gvsig.fmap.core.ICanReproject;
68
import com.iver.cit.gvsig.fmap.core.IFeature;
69
import com.iver.cit.gvsig.fmap.core.IGeometry;
70
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
71
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
72
import com.iver.cit.gvsig.fmap.drivers.IFeatureIterator;
73
import com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver;
74
import com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver;
75
import com.iver.cit.gvsig.fmap.drivers.WKBParser2;
76
import com.iver.cit.gvsig.fmap.layers.FLayer;
77
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
78
import com.iver.cit.gvsig.fmap.layers.ISpatialDB;
79
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
80

    
81

    
82
/**
83
 * @author FJP
84
 *
85
 * TODO To change the template for this generated type comment go to
86
 * Window - Preferences - Java - Code Generation - Code and Comments
87
 */
88
public class testPostGis {
89

    
90
      public static void main(String[] args) 
91
      { 
92
      /*    System.err.println("dburl has the following format:");
93
          System.err.println("jdbc:postgresql://HOST:PORT/DATABASENAME");
94
          System.err.println("tablename is 'jdbc_test' by default.");
95
          System.exit(1); */
96

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

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

    
157
              
158

    
159
            /* 
160
            * Create a statement and execute a select query. 
161
            */
162
              // String strSQL = "select AsBinary(the_geom) as geom, nom_provin from " + dbtable;
163
              // String strSQL = "select ASBINARY(the_geom) as geom, gid from " + dbtable;
164
              String strSQL = "select ASBINARY(geometria) as geom, fecha_inicio_evento, fecha_fin_evento, date1, time1 from " + dbtable;
165
              // strSQL = "select ASTEXT(the_geom), nom_provin as geom from " + dbtable;
166
              /* String strSQL = "SELECT gid, rd_3, rd_5, rd_6, rd_10, rd_11, rd_12, rd_13, rd_14,"; 
167
              strSQL = strSQL + " rd_15, rd_16, kilometers, cost, metros, AsText(force_2d(the_geom)) FROM vias"; 
168
              strSQL = strSQL + " WHERE TRUE";
169
              */
170
              // PreparedStatement s = conn.prepareStatement(strSQL);
171
              
172
              Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
173
              // s.execute("begin");
174
              
175
              // Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
176
              // s.setFetchSize(5);
177
              int fetchSize = 150000;
178
            s.execute("declare wkb_cursor binary cursor for " + strSQL);
179
            ResultSet r =   s.executeQuery("fetch forward " + fetchSize + " in wkb_cursor");
180
//              /// ResultSet r =   s.executeQuery("fetch forward all in wkb_cursor");
181
            
182
            // String strSQL2 = "select AsBinary(the_geom) as geom, nom_provin from " + dbtable;
183
            // PreparedStatement ps = conn.prepareStatement(strSQL2);
184
            // ResultSet r = ps.executeQuery();
185
                        
186
//              ResultSet r = s.executeQuery(strSQL);
187
            WKBParser2 parser2 = new WKBParser2();
188
            // WKBParser parser = new WKBParser();
189
            long id=0;
190
            /* for (int i=1; i< 100; i++)
191
            {
192
                r.absolute(i);
193
                System.out.println("Row " + i + ":" + r.getString(2));
194
            }
195
            r.beforeFirst();
196
              for (int i=1; i< 100; i++)
197
              {
198
                  r.absolute(i);
199
                  System.out.println("Row " + i + ":" + r.getString(2));
200
              } */
201
            Timestamp date1 = new Timestamp(2006-1900, 8, 5, 16, 0, 0, 0);
202
            long time1 = date1.getTime();
203
            System.out.println("time1 = " + time1 + " data1 + " + date1);
204
            Timestamp date2 = new Timestamp(2006-1900, 8, 4, 9, 0, 0, 0);
205
            long time2 = date2.getTime();
206
            System.out.println("time2 = " + time2 + " data2 + " + date2);
207
            double num_msSecs2000 = 9.466776E11;
208

    
209
              
210
            while( r.next() ) 
211
            { 
212
              /* 
213
              * Retrieve the geometry as an object then cast it to the geometry type. 
214
              * Print things out. 
215
              */ 
216
                // Object obj = r.getObject(2);
217
                // byte[] arrayByte = r.getBytes(1);
218
                
219
                // IGeometry gp = parser.parse(arrayByte);
220
                // IGeometry gp2 = parser2.parse(arrayByte);
221
                    
222
                String strAux = r.getString(2);
223
//                long asLong = r.getLong(2);
224
//                double asDouble = r.getDouble(2);
225
//                Date asDate = r.getDate(2);
226
                byte[] data1 = r.getBytes(2);
227
                byte[] data2 = r.getBytes(3);
228
                byte[] bdate1 = r.getBytes(4);
229
                byte[] btime1 = r.getBytes(5);
230
                ByteBuffer buf = ByteBuffer.wrap(data1);
231
                ByteBuffer bufDate1 = ByteBuffer.wrap(bdate1);
232
                ByteBuffer bufTime1 = ByteBuffer.wrap(btime1);
233
                
234
                long daysAfter2000 = bufDate1.getInt() + 1;
235
                long msecs = daysAfter2000*24*60*60*1000;
236
                long real_msecs_date1 = (long) (num_msSecs2000 + msecs);
237
                Date realDate1 = new Date(real_msecs_date1);
238
                System.err.println("Date1 = " + realDate1 + " diff = " + (real_msecs_date1 - num_msSecs2000));
239
                
240
                long microsecs = bufTime1.getLong();
241
                long real_msecs = (long) (microsecs-num_msSecs2000);
242
                Time mytime1 = new Time(real_msecs);
243
                System.err.println("TIME1 = " + mytime1);
244

    
245
                                
246
                                double n1 = buf.getDouble(0); // num segs after 2000
247
//                                Timestamp ts2000 = new Timestamp(2000-1900, 0, 1, 0, 0 , 0, 0);
248
//                                int offset = ts2000.getTimezoneOffset() * 60 * 1000;
249
                                
250
//                                double num_msSecs2000 = ts2000.getTime() + offset;
251
                                long real_msecs2 = (long) (num_msSecs2000 + n1*1000);
252
                                Timestamp real = new Timestamp(real_msecs2);
253

    
254
                // int id = r.getInt(2);
255
                System.out.println("Fila " + id + ": fecha:" + real);
256
                id++;
257
                // Geometry regeom = PGgeometry.geomFromString(obj.toString());
258
                
259
              // PGgeometry geom = (PGgeometry)obj; 
260
               // int id = r.getInt(2);
261
              // System.out.println("Row " + id + ":" + strAux); 
262
              // System.out.println(geom.toString()); 
263
                // System.out.println("provin=" + r.getString(2));
264
                /* if ((id % fetchSize) == 0)
265
                {
266
                    r =   s.executeQuery("fetch forward " + fetchSize + " in wkb_cursor");
267
                } */
268
                            
269
            }
270
            // s.execute("end");
271
            s.close();
272
            
273
          } 
274
          catch( Exception e ) 
275
          { 
276
            e.printStackTrace(); 
277
          }  
278
        }
279
      private static void test2(Connection conn, String dburl, String dbuser, String dbpass, String dbtable)
280
      {          
281
          try 
282
          { 
283
            /* 
284
            * Create a statement and execute a select query. 
285
            */
286
              String strSQL = "select gid from " + dbtable;
287
              PreparedStatement s = conn.prepareStatement(strSQL);
288
              
289
              // Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
290
              int fetchSize = 5000;
291
              ResultSet r = s.executeQuery(strSQL);
292
              int id=0;
293
              while( r.next() ) 
294
              { 
295
                String strAux = r.getString(1);
296
                id++;
297
                // System.out.println("Row " + id + ":" + strAux); 
298
              } 
299
              s.close();
300
          } 
301
          catch( Exception e ) 
302
          { 
303
            e.printStackTrace(); 
304
          }  
305
        }
306

    
307
      
308
      private static void test3(Connection conn, String dburl, String dbuser, String dbpass, String dbtable)
309
      {          
310
          try 
311
          { 
312
                  Fastpath  fp;
313
                  if (conn.getClass().getName().equals("org.postgresql.jdbc2.Connection")) {
314
                          // ((org.postgresql.Connection) conn).addDataType("geometry", "org.postgis.PGgeometry");
315
                          // ((org.postgresql.Connection) conn).addDataType("box3d", "org.postgis.PGbox3d");
316
                  } else {
317
                          ((org.postgresql.PGConnection) conn).addDataType("geometry", "org.postgis.PGgeometry");
318
                          ((org.postgresql.PGConnection) conn).addDataType("box3d", "org.postgis.PGbox3d");
319
                          fp =  ((org.postgresql.PGConnection) conn).getFastpathAPI();
320
                  } 
321

    
322
              
323

    
324
            /* 
325
            * Create a statement and execute a select query. 
326
            */
327
              String strSQL = "select * from " + dbtable;
328
              // String strSQL = "select ASBINARY(the_geom) as geom from " + dbtable;
329
              // strSQL = "select ASTEXT(the_geom), nom_provin as geom from " + dbtable;
330
              /* String strSQL = "SELECT gid, rd_3, rd_5, rd_6, rd_10, rd_11, rd_12, rd_13, rd_14,"; 
331
              strSQL = strSQL + " rd_15, rd_16, kilometers, cost, metros, AsText(force_2d(the_geom)) FROM vias"; 
332
              strSQL = strSQL + " WHERE TRUE";
333
              */
334
              // PreparedStatement s = conn.prepareStatement(strSQL);
335
              
336
              Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
337
              // s.execute("begin");
338
              
339
              // Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
340
              // s.setFetchSize(5);
341
            /*  int fetchSize = 150000;
342
            s.execute("declare wkb_cursor2 binary cursor for " + strSQL);
343
            ResultSet r =   s.executeQuery("fetch forward " + fetchSize + " in wkb_cursor2"); */
344
            
345
            // String strSQL2 = "select AsBinary(the_geom) as geom, nom_provin from " + dbtable;
346
            // PreparedStatement ps = conn.prepareStatement(strSQL2);
347
            // ResultSet r = ps.executeQuery();
348
                        
349
            ResultSet r = s.executeQuery(strSQL);
350
            // WKBParser parser = new WKBParser();
351
            long id=0;
352
            /* FastpathArg args[] = new FastpathArg[2];
353
            args[0] = new FastpathArg(fd);
354
            args[1] = new FastpathArg(len);
355
            return fp.getData("loread", args); */  
356
            while( r.next() ) 
357
            { 
358
              /* 
359
              * Retrieve the geometry as an object then cast it to the geometry type. 
360
              * Print things out. 
361
              */ 
362
                Object obj = r.getObject(9);
363
                // fp.
364
                    // final Shape current = (Shape) r.getObject(1);
365
                // byte[] arrayByte = r.getBytes(1);
366
                // String strAux = r.getString(2);
367
                
368
                id++;
369
                // Geometry regeom = PGgeometry.geomFromString(obj.toString());
370
                
371
              // PGgeometry geom = (PGgeometry)obj; 
372
               // int id = r.getInt(2);
373
              // System.out.println("Row " + id + ":" + strAux); 
374
              // System.out.println(geom.toString()); 
375
                // System.out.println("provin=" + r.getString(2));
376
                /* if ((id % fetchSize) == 0)
377
                {
378
                    r =   s.executeQuery("fetch forward " + fetchSize + " in wkb_cursor");
379
                } */
380
                
381
                            
382
            }
383
            // s.execute("end");
384
            s.close();
385
            
386
          } 
387
          catch( Exception e ) 
388
          { 
389
            e.printStackTrace(); 
390
          }  
391
      }
392
      
393
      private static void test4(FLyrVect lyr)
394
      {
395
            try
396
            {
397
                    ISpatialDB dbAdapter = (ISpatialDB) lyr.getSource();
398
            VectorialDatabaseDriver dbDriver = (VectorialDatabaseDriver) dbAdapter.getDriver();
399
                IFeatureIterator geomIt = dbDriver.getFeatureIterator(lyr.getFullExtent(), "23030");
400
                while (geomIt.hasNext())
401
                {
402
                        IFeature feat = geomIt.next();
403
                        IGeometry geom = feat.getGeometry();
404
                }
405
                  }
406
                  catch(Exception e)
407
                  {
408
                          e.printStackTrace();
409
                  }
410

    
411
      }
412

    
413
        private static FLyrVect initLayerPostGIS()
414
        {
415
        String dbURL = "jdbc:postgresql://localhost:5432/latin1"; // latin1 is the catalog name 
416
        String user = "postgres";
417
        String pwd = "aquilina";
418
        String layerName = "vias";
419
        String tableName = "vias";
420
        Connection conn;
421
        LayerFactory.setDriversPath("D:/eclipse/workspace/_fwAndami/gvSIG/extensiones/com.iver.cit.gvsig/drivers");
422
                try {
423
                        conn = DriverManager.getConnection(dbURL, user, pwd);
424
                conn.setAutoCommit(false);
425
                
426
                String fidField = "gid"; // BE CAREFUL => MAY BE NOT!!!
427
                String geomField = "the_geom"; // BE CAREFUL => MAY BE NOT!!! => You should read table GEOMETRY_COLUMNS.
428
                                                                                // See PostGIS help.
429

    
430
                // To obtain the fields, make a connection and get them. 
431
                        /* Statement st = conn.createStatement();
432
                        ResultSet rs = st.executeQuery("select * from " + tableName + " LIMIT 1");
433
                        ResultSetMetaData rsmd = rs.getMetaData();
434
                        String[] fields = new String[rsmd.getColumnCount()-1]; // We don't want to include the_geom field
435
                        int j = 0;
436
                        for (int i = 0; i < fields.length; i++) {
437
                                if (!rsmd.getColumnName(i+1).equalsIgnoreCase(geomField))
438
                                {
439
                                        fields[j++] = rsmd.getColumnName(i+1);                                        
440
                                }
441
                        }
442
                        rs.close(); */        
443
                
444
                String[] fields = new String[1];                
445
                fields[0] = "gid"; 
446
                
447
                String whereClause = "";
448
        
449
                VectorialJDBCDriver driver = (VectorialJDBCDriver) LayerFactory.getDM()
450
                                        .getDriver("PostGIS JDBC Driver");
451
                
452
                // Here you can set the workingArea
453
                // driver.setWorkingArea(dbLayerDefinition.getWorkingArea());
454
                
455
                
456
                String strEPSG = "23030";
457
                DBLayerDefinition lyrDef = new DBLayerDefinition();                
458
                lyrDef.setName(layerName);
459
                lyrDef.setTableName(tableName);
460
                lyrDef.setWhereClause(whereClause);
461
                lyrDef.setFieldNames(fields);
462
                lyrDef.setFieldGeometry(geomField);
463
                lyrDef.setFieldID(fidField);
464
                // if (dbLayerDefinition.getWorkingArea() != null)
465
                //     lyrDef.setWorkingArea(dbLayerDefinition.getWorkingArea());
466
                
467
                lyrDef.setSRID_EPSG(strEPSG);
468
                if (driver instanceof ICanReproject)
469
                {                    
470
                    ((ICanReproject)driver).setDestProjection(strEPSG);
471
                }
472
                driver.setData(conn, lyrDef);
473
                IProjection proj = null; 
474
                if (driver instanceof ICanReproject)
475
                {                                        
476
                    proj = CRSFactory.getCRS("EPSG:" + ((ICanReproject)driver).getSourceProjection()); 
477
                }
478
                
479
                FLayer lyr = LayerFactory.createDBLayer(driver, layerName, proj);
480
                Rectangle2D rectAux = lyr.getFullExtent();
481
                return (FLyrVect) lyr;
482
                }
483
                catch(Exception e)
484
                {
485
                        e.printStackTrace();
486
                }
487
                return null;
488
        }
489
}