Statistics
| Revision:

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

History | View | Annotate | Download (19.6 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 org.cresques.cts.IProjection;
62
import org.postgresql.fastpath.Fastpath;
63

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

    
78

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

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

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

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

    
154
              
155

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

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

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

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

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

    
327
              
328

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

    
416
      }
417

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

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