Statistics
| Revision:

root / trunk / extensions / extJDBC / src / com / iver / cit / gvsig / fmap / drivers / jdbc / postgis / testPostGis.java @ 7161

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

    
63
import javax.swing.UIManager;
64

    
65
import org.cresques.cts.IProjection;
66
import org.cresques.cts.ProjectionPool;
67
import org.postgresql.fastpath.Fastpath;
68

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

    
82

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

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

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

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

    
158
              
159

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

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

    
254
                                
255
                                double n1 = buf.getDouble(0); // num segs after 2000
256
//                                Timestamp ts2000 = new Timestamp(2000-1900, 0, 1, 0, 0 , 0, 0);
257
//                                int offset = ts2000.getTimezoneOffset() * 60 * 1000;
258
                                
259
//                                double num_msSecs2000 = ts2000.getTime() + offset;
260
                                long real_msecs2 = (long) (num_msSecs2000 + n1*1000);
261
                                Timestamp real = new Timestamp(real_msecs2);
262

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

    
316
      
317
      private static void test3(Connection conn, String dburl, String dbuser, String dbpass, String dbtable)
318
      {          
319
          try 
320
          { 
321
                  Fastpath  fp;
322
                  if (conn.getClass().getName().equals("org.postgresql.jdbc2.Connection")) {
323
                          // ((org.postgresql.Connection) conn).addDataType("geometry", "org.postgis.PGgeometry");
324
                          // ((org.postgresql.Connection) conn).addDataType("box3d", "org.postgis.PGbox3d");
325
                  } else {
326
                          ((org.postgresql.PGConnection) conn).addDataType("geometry", "org.postgis.PGgeometry");
327
                          ((org.postgresql.PGConnection) conn).addDataType("box3d", "org.postgis.PGbox3d");
328
                          fp =  ((org.postgresql.PGConnection) conn).getFastpathAPI();
329
                  } 
330

    
331
              
332

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

    
420
      }
421

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

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