Statistics
| Revision:

root / branches / v10 / extensions / extJDBC / src / com / iver / cit / gvsig / fmap / drivers / jdbc / postgis / testPostGis.java @ 8913

History | View | Annotate | Download (20 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.crs.CRSFactory;
73
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
74
import com.iver.cit.gvsig.fmap.drivers.IFeatureIterator;
75
import com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver;
76
import com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver;
77
import com.iver.cit.gvsig.fmap.drivers.WKBParser2;
78
import com.iver.cit.gvsig.fmap.layers.FLayer;
79
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
80
import com.iver.cit.gvsig.fmap.layers.ISpatialDB;
81
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
82

    
83

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

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

    
99
          
100
//          String dburl = "jdbc:postgresql://localhost/latin1";
101
//          String dbuser = "postgres";
102
//          String dbpass = "aquilina";
103
              
104
        String dburl = "jdbc:postgresql://192.168.0.217/postgis";
105
        String dbuser = "gvsig";
106
        String dbpass = "";
107

    
108
    
109
          String dbtable = "carreteras_lin_5k_t10";
110
          
111
          Connection conn = null; 
112
          System.out.println("Creating JDBC connection...");
113
          try {
114
            Class.forName("org.postgresql.Driver");
115
              Enumeration enumDrivers = DriverManager.getDrivers();
116
              while (enumDrivers.hasMoreElements())
117
              {
118
                  System.out.println("Driver " + enumDrivers.nextElement().toString());
119
              }
120
              conn = DriverManager.getConnection(dburl, dbuser, dbpass);
121
          
122
              conn.setAutoCommit(false);
123
          
124
              long t1 = System.currentTimeMillis();
125
              test1(conn, dburl, dbuser, dbpass, dbtable);
126
              long t2 = System.currentTimeMillis();          
127
              System.out.println("Tiempo de consulta1:" + (t2 - t1) + " milisegundos");
128
              
129
              /* FLyrVect lyr = initLayerPostGIS();
130
              t1 = System.currentTimeMillis();
131
              test4(lyr);
132
              t2 = System.currentTimeMillis();
133
    
134
              System.out.println("Tiempo de consulta2:" + (t2 - t1) + " milisegundos"); */
135
               
136
              conn.close();
137

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

    
164
              
165

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

    
217
              
218
            while( r.next() ) 
219
            { 
220
              /* 
221
              * Retrieve the geometry as an object then cast it to the geometry type. 
222
              * Print things out. 
223
              */ 
224
                // Object obj = r.getObject(2);
225
                byte[] arrayByte = r.getBytes(1);
226
                
227
                // IGeometry gp = parser.parse(arrayByte);
228
                IGeometry gp2 = parser2.parse(arrayByte);
229
                    
230
//                String strAux = r.getString(5);
231
//                System.out.println("Straux = " + strAux);
232
//                long asLong = r.getLong(2);
233
//                double asDouble = r.getDouble(2);
234
//                Date asDate = r.getDate(2);
235
//                byte[] data1 = r.getBytes(2);
236
//                byte[] data2 = r.getBytes(3);
237
//                byte[] bdate1 = r.getBytes(4);
238
//                byte[] btime1 = r.getBytes(5);
239
//                ByteBuffer buf = ByteBuffer.wrap(data1);
240
//                ByteBuffer bufDate1 = ByteBuffer.wrap(bdate1);
241
//                ByteBuffer bufTime1 = ByteBuffer.wrap(btime1);
242
//                
243
//                long daysAfter2000 = bufDate1.getInt() + 1;
244
//                long msecs = daysAfter2000*24*60*60*1000;
245
//                long real_msecs_date1 = (long) (num_msSecs2000 + msecs);
246
//                Date realDate1 = new Date(real_msecs_date1);
247
//                System.err.println("Date1 = " + realDate1 + " diff = " + (real_msecs_date1 - num_msSecs2000));
248
//                
249
//                Calendar cal = new GregorianCalendar();
250
//                cal.setTimeInMillis(0);
251
//                // bufTime1.order(ByteOrder.LITTLE_ENDIAN);
252
//                long microsecs = bufTime1.getLong();
253
//                long real_msecs = microsecs - 3600000; // le quitamos una hora.
254
//                cal.setTimeInMillis(real_msecs);
255
//                long milis = cal.getTimeInMillis();
256
//                Time mytime1 = new Time(real_msecs);
257
//                Date mytime1asdate = new Date(real_msecs);
258
//                System.err.println("microsecs = " + microsecs + " TIME1 = " + mytime1);
259
//                System.err.println("microsecs = " + (long)num_msSecs2000 + " TIME1ASDATE = " + mytime1asdate);
260
//
261
//                                
262
//                                double n1 = buf.getDouble(0); // num segs after 2000
263
////                                Timestamp ts2000 = new Timestamp(2000-1900, 0, 1, 0, 0 , 0, 0);
264
////                                int offset = ts2000.getTimezoneOffset() * 60 * 1000;
265
//                                
266
////                                double num_msSecs2000 = ts2000.getTime() + offset;
267
//                                long real_msecs2 = (long) (num_msSecs2000 + n1*1000);
268
//                                Timestamp real = new Timestamp(real_msecs2);
269
//
270
//                // int id = r.getInt(2);
271
//                System.out.println("Fila " + id + ": fecha:" + real);
272
//                id++;
273
//                // Geometry regeom = PGgeometry.geomFromString(obj.toString());
274
//                
275
//              // PGgeometry geom = (PGgeometry)obj; 
276
//               // int id = r.getInt(2);
277
//              // System.out.println("Row " + id + ":" + strAux); 
278
//              // System.out.println(geom.toString()); 
279
//                // System.out.println("provin=" + r.getString(2));
280
//                /* if ((id % fetchSize) == 0)
281
//                {
282
//                    r =   s.executeQuery("fetch forward " + fetchSize + " in wkb_cursor");
283
//                } */
284
                            
285
            }
286
            // s.execute("end");
287
            s.close();
288
            
289
          } 
290
          catch( Exception e ) 
291
          { 
292
            e.printStackTrace(); 
293
          }  
294
        }
295
      private static void test2(Connection conn, String dburl, String dbuser, String dbpass, String dbtable)
296
      {          
297
          try 
298
          { 
299
            /* 
300
            * Create a statement and execute a select query. 
301
            */
302
              String strSQL = "select gid from " + dbtable;
303
              PreparedStatement s = conn.prepareStatement(strSQL);
304
              
305
              // Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
306
              int fetchSize = 5000;
307
              ResultSet r = s.executeQuery(strSQL);
308
              int id=0;
309
              while( r.next() ) 
310
              { 
311
                String strAux = r.getString(1);
312
                id++;
313
                // System.out.println("Row " + id + ":" + strAux); 
314
              } 
315
              s.close();
316
          } 
317
          catch( Exception e ) 
318
          { 
319
            e.printStackTrace(); 
320
          }  
321
        }
322

    
323
      
324
      private static void test3(Connection conn, String dburl, String dbuser, String dbpass, String dbtable)
325
      {          
326
          try 
327
          { 
328
                  Fastpath  fp;
329
                  if (conn.getClass().getName().equals("org.postgresql.jdbc2.Connection")) {
330
                          // ((org.postgresql.Connection) conn).addDataType("geometry", "org.postgis.PGgeometry");
331
                          // ((org.postgresql.Connection) conn).addDataType("box3d", "org.postgis.PGbox3d");
332
                  } else {
333
                          ((org.postgresql.PGConnection) conn).addDataType("geometry", "org.postgis.PGgeometry");
334
                          ((org.postgresql.PGConnection) conn).addDataType("box3d", "org.postgis.PGbox3d");
335
                          fp =  ((org.postgresql.PGConnection) conn).getFastpathAPI();
336
                  } 
337

    
338
              
339

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

    
427
      }
428

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

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