Statistics
| Revision:

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

History | View | Annotate | Download (19.4 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 org.cresques.cts.IProjection;
64
import org.postgresql.fastpath.Fastpath;
65

    
66
import com.iver.cit.gvsig.fmap.core.ICanReproject;
67
import com.iver.cit.gvsig.fmap.core.IFeature;
68
import com.iver.cit.gvsig.fmap.core.IGeometry;
69
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
70
import com.iver.cit.gvsig.fmap.drivers.ConnectionFactory;
71
import com.iver.cit.gvsig.fmap.drivers.ConnectionJDBC;
72
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
73
import com.iver.cit.gvsig.fmap.drivers.IConnection;
74
import com.iver.cit.gvsig.fmap.drivers.IFeatureIterator;
75
import com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver;
76
import com.iver.cit.gvsig.fmap.drivers.IVectorialJDBCDriver;
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
          String dbtable = "VIAS";
111

    
112
          Connection conn = null;
113
          System.out.println("Creating JDBC connection...");
114
          try {
115
            Class.forName("org.postgresql.Driver");
116
              Enumeration enumDrivers = DriverManager.getDrivers();
117
              while (enumDrivers.hasMoreElements())
118
              {
119
                  System.out.println("Driver " + enumDrivers.nextElement().toString());
120
              }
121
              conn = DriverManager.getConnection(dburl, dbuser, dbpass);
122

    
123
              conn.setAutoCommit(false);
124

    
125
              long t1 = System.currentTimeMillis();
126
              test1(conn, dburl, dbuser, dbpass, dbtable);
127
              long t2 = System.currentTimeMillis();
128
              System.out.println("Tiempo de consulta1:" + (t2 - t1) + " milisegundos");
129

    
130
              /* FLyrVect lyr = initLayerPostGIS();
131
              t1 = System.currentTimeMillis();
132
              test4(lyr);
133
              t2 = System.currentTimeMillis();
134

135
              System.out.println("Tiempo de consulta2:" + (t2 - t1) + " milisegundos"); */
136

    
137
              conn.close();
138

    
139
          } catch (ClassNotFoundException e) {
140
              // TODO Auto-generated catch block
141
              e.printStackTrace();
142
          } catch (SQLException e) {
143
            // TODO Auto-generated catch block
144
            e.printStackTrace();
145
          }
146

    
147

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

    
165

    
166

    
167
            /*
168
            * Create a statement and execute a select query.
169
            */
170
              // String strSQL = "select AsBinary(the_geom) as geom, nom_provin from " + dbtable;
171
              // String strSQL = "select ASBINARY(the_geom) as geom, gid from " + dbtable;
172
              // String strSQL = "select ASBINARY(geometria) as geom, fecha_inicio_evento, fecha_fin_evento, date1, time1 from " + dbtable;
173
                  String strSQL = "select ASBINARY(the_geom) as geom from " + dbtable;
174
              // strSQL = "select ASTEXT(the_geom), nom_provin as geom from " + dbtable;
175
              /* String strSQL = "SELECT gid, rd_3, rd_5, rd_6, rd_10, rd_11, rd_12, rd_13, rd_14,";
176
              strSQL = strSQL + " rd_15, rd_16, kilometers, cost, metros, AsText(force_2d(the_geom)) FROM vias";
177
              strSQL = strSQL + " WHERE TRUE";
178
              */
179
              // PreparedStatement s = conn.prepareStatement(strSQL);
180

    
181
              Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
182
              // s.execute("begin");
183

    
184
              // Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
185
              // s.setFetchSize(5);
186
              int fetchSize = 150000;
187
            s.execute("declare wkb_cursor binary cursor for " + strSQL);
188
            ResultSet r =   s.executeQuery("fetch forward " + fetchSize + " in wkb_cursor");
189
//              /// ResultSet r =   s.executeQuery("fetch forward all in wkb_cursor");
190

    
191
            // String strSQL2 = "select AsBinary(the_geom) as geom, nom_provin from " + dbtable;
192
            // PreparedStatement ps = conn.prepareStatement(strSQL2);
193
            // ResultSet r = ps.executeQuery();
194

    
195
//              ResultSet r = s.executeQuery(strSQL);
196
            WKBParser2 parser2 = new WKBParser2();
197
            // WKBParser parser = new WKBParser();
198
            long id=0;
199
            /* for (int i=1; i< 100; i++)
200
            {
201
                r.absolute(i);
202
                System.out.println("Row " + i + ":" + r.getString(2));
203
            }
204
            r.beforeFirst();
205
              for (int i=1; i< 100; i++)
206
              {
207
                  r.absolute(i);
208
                  System.out.println("Row " + i + ":" + r.getString(2));
209
              } */
210
            Timestamp date1 = new Timestamp(2006-1900, 8, 5, 16, 0, 0, 0);
211
            long time1 = date1.getTime();
212
            System.out.println("time1 = " + time1 + " data1 + " + date1);
213
            Timestamp date2 = new Timestamp(2006-1900, 8, 4, 9, 0, 0, 0);
214
            long time2 = date2.getTime();
215
            System.out.println("time2 = " + time2 + " data2 + " + date2);
216
            double num_msSecs2000 = 9.466776E11;
217

    
218

    
219
            while( r.next() )
220
            {
221
              /*
222
              * Retrieve the geometry as an object then cast it to the geometry type.
223
              * Print things out.
224
              */
225
                // Object obj = r.getObject(2);
226
                byte[] arrayByte = r.getBytes(1);
227

    
228
                // IGeometry gp = parser.parse(arrayByte);
229
                IGeometry gp2 = parser2.parse(arrayByte);
230

    
231
//                String strAux = r.getString(5);
232
//                System.out.println("Straux = " + strAux);
233
//                long asLong = r.getLong(2);
234
//                double asDouble = r.getDouble(2);
235
//                Date asDate = r.getDate(2);
236
                //                byte[] data1 = r.getBytes(2);
237
//                byte[] data2 = r.getBytes(3);
238
//                byte[] bdate1 = r.getBytes(4);
239
//                byte[] btime1 = r.getBytes(5);
240
//                ByteBuffer buf = ByteBuffer.wrap(data1);
241
//                ByteBuffer bufDate1 = ByteBuffer.wrap(bdate1);
242
//                ByteBuffer bufTime1 = ByteBuffer.wrap(btime1);
243
//
244
//                long daysAfter2000 = bufDate1.getInt() + 1;
245
//                long msecs = daysAfter2000*24*60*60*1000;
246
//                long real_msecs_date1 = (long) (num_msSecs2000 + msecs);
247
//                Date realDate1 = new Date(real_msecs_date1);
248
//                System.err.println("Date1 = " + realDate1 + " diff = " + (real_msecs_date1 - num_msSecs2000));
249
//
250
//                Calendar cal = new GregorianCalendar();
251
//                cal.setTimeInMillis(0);
252
//                // bufTime1.order(ByteOrder.LITTLE_ENDIAN);
253
//                long microsecs = bufTime1.getLong();
254
//                long real_msecs = microsecs - 3600000; // le quitamos una hora.
255
//                cal.setTimeInMillis(real_msecs);
256
//                long milis = cal.getTimeInMillis();
257
//                Time mytime1 = new Time(real_msecs);
258
//                Date mytime1asdate = new Date(real_msecs);
259
//                System.err.println("microsecs = " + microsecs + " TIME1 = " + mytime1);
260
//                System.err.println("microsecs = " + (long)num_msSecs2000 + " TIME1ASDATE = " + mytime1asdate);
261
//
262
//
263
//                                double n1 = buf.getDouble(0); // num segs after 2000
264
////                                Timestamp ts2000 = new Timestamp(2000-1900, 0, 1, 0, 0 , 0, 0);
265
////                                int offset = ts2000.getTimezoneOffset() * 60 * 1000;
266
//
267
////                                double num_msSecs2000 = ts2000.getTime() + offset;
268
//                                long real_msecs2 = (long) (num_msSecs2000 + n1*1000);
269
//                                Timestamp real = new Timestamp(real_msecs2);
270
//
271
//                // int id = r.getInt(2);
272
//                System.out.println("Fila " + id + ": fecha:" + real);
273
//                id++;
274
//                // Geometry regeom = PGgeometry.geomFromString(obj.toString());
275
//
276
//              // PGgeometry geom = (PGgeometry)obj;
277
//               // int id = r.getInt(2);
278
//              // System.out.println("Row " + id + ":" + strAux);
279
//              // System.out.println(geom.toString());
280
//                // System.out.println("provin=" + r.getString(2));
281
//                /* if ((id % fetchSize) == 0)
282
//                {
283
//                    r =   s.executeQuery("fetch forward " + fetchSize + " in wkb_cursor");
284
//                } */
285

    
286
            }
287
            // s.execute("end");
288
            s.close();
289

    
290
          }
291
          catch( Exception e )
292
          {
293
            e.printStackTrace();
294
          }
295
        }
296
      private static void test2(Connection conn, String dburl, String dbuser, String dbpass, String dbtable)
297
      {
298
          try
299
          {
300
            /*
301
            * Create a statement and execute a select query.
302
            */
303
              String strSQL = "select gid from " + dbtable;
304
              PreparedStatement s = conn.prepareStatement(strSQL);
305

    
306
              // Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
307
              int fetchSize = 5000;
308
              ResultSet r = s.executeQuery(strSQL);
309
              int id=0;
310
              while( r.next() )
311
              {
312
                String strAux = r.getString(1);
313
                id++;
314
                // System.out.println("Row " + id + ":" + strAux);
315
              }
316
              s.close();
317
          }
318
          catch( Exception e )
319
          {
320
            e.printStackTrace();
321
          }
322
        }
323

    
324

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

    
339

    
340

    
341
            /*
342
            * Create a statement and execute a select query.
343
            */
344
              String strSQL = "select * from " + dbtable;
345
              // String strSQL = "select ASBINARY(the_geom) as geom from " + dbtable;
346
              // strSQL = "select ASTEXT(the_geom), nom_provin as geom from " + dbtable;
347
              /* String strSQL = "SELECT gid, rd_3, rd_5, rd_6, rd_10, rd_11, rd_12, rd_13, rd_14,";
348
              strSQL = strSQL + " rd_15, rd_16, kilometers, cost, metros, AsText(force_2d(the_geom)) FROM vias";
349
              strSQL = strSQL + " WHERE TRUE";
350
              */
351
              // PreparedStatement s = conn.prepareStatement(strSQL);
352

    
353
              Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
354
              // s.execute("begin");
355

    
356
              // Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
357
              // s.setFetchSize(5);
358
            /*  int fetchSize = 150000;
359
            s.execute("declare wkb_cursor2 binary cursor for " + strSQL);
360
            ResultSet r =   s.executeQuery("fetch forward " + fetchSize + " in wkb_cursor2"); */
361

    
362
            // String strSQL2 = "select AsBinary(the_geom) as geom, nom_provin from " + dbtable;
363
            // PreparedStatement ps = conn.prepareStatement(strSQL2);
364
            // ResultSet r = ps.executeQuery();
365

    
366
            ResultSet r = s.executeQuery(strSQL);
367
            // WKBParser parser = new WKBParser();
368
            long id=0;
369
            /* FastpathArg args[] = new FastpathArg[2];
370
            args[0] = new FastpathArg(fd);
371
            args[1] = new FastpathArg(len);
372
            return fp.getData("loread", args); */
373
            while( r.next() )
374
            {
375
              /*
376
              * Retrieve the geometry as an object then cast it to the geometry type.
377
              * Print things out.
378
              */
379
                Object obj = r.getObject(9);
380
                // fp.
381
                    // final Shape current = (Shape) r.getObject(1);
382
                // byte[] arrayByte = r.getBytes(1);
383
                // String strAux = r.getString(2);
384

    
385
                id++;
386
                // Geometry regeom = PGgeometry.geomFromString(obj.toString());
387

    
388
              // PGgeometry geom = (PGgeometry)obj;
389
               // int id = r.getInt(2);
390
              // System.out.println("Row " + id + ":" + strAux);
391
              // System.out.println(geom.toString());
392
                // System.out.println("provin=" + r.getString(2));
393
                /* if ((id % fetchSize) == 0)
394
                {
395
                    r =   s.executeQuery("fetch forward " + fetchSize + " in wkb_cursor");
396
                } */
397

    
398

    
399
            }
400
            // s.execute("end");
401
            s.close();
402

    
403
          }
404
          catch( Exception e )
405
          {
406
            e.printStackTrace();
407
          }
408
      }
409

    
410
      private static void test4(FLyrVect lyr)
411
      {
412
            try
413
            {
414
                    ISpatialDB dbAdapter = (ISpatialDB) lyr.getSource();
415
            IVectorialDatabaseDriver dbDriver = (IVectorialDatabaseDriver) dbAdapter.getDriver();
416
                IFeatureIterator geomIt = dbDriver.getFeatureIterator(lyr.getFullExtent(), "23030");
417
                while (geomIt.hasNext())
418
                {
419
                        IFeature feat = geomIt.next();
420
                        IGeometry geom = feat.getGeometry();
421
                }
422
                  }
423
                  catch(Exception e)
424
                  {
425
                          e.printStackTrace();
426
                  }
427

    
428
      }
429

    
430
        private static FLyrVect initLayerPostGIS()
431
        {
432
        String dbURL = "jdbc:postgresql://localhost:5432/latin1"; // latin1 is the catalog name
433
        String user = "postgres";
434
        String pwd = "aquilina";
435
        String layerName = "vias";
436
        String tableName = "vias";
437
        IConnection conn;
438
        LayerFactory.setDriversPath("D:/eclipse/workspace/_fwAndami/gvSIG/extensiones/com.iver.cit.gvsig/drivers");
439
                try {
440
                        conn = ConnectionFactory.createConnection(dbURL, user, pwd);
441
                        ((ConnectionJDBC)conn).getConnection().setAutoCommit(false);
442

    
443
                String fidField = "gid"; // BE CAREFUL => MAY BE NOT!!!
444
                String geomField = "the_geom"; // BE CAREFUL => MAY BE NOT!!! => You should read table GEOMETRY_COLUMNS.
445
                                                                                // See PostGIS help.
446

    
447
                // To obtain the fields, make a connection and get them.
448
                        /* Statement st = conn.createStatement();
449
                        ResultSet rs = st.executeQuery("select * from " + tableName + " LIMIT 1");
450
                        ResultSetMetaData rsmd = rs.getMetaData();
451
                        String[] fields = new String[rsmd.getColumnCount()-1]; // We don't want to include the_geom field
452
                        int j = 0;
453
                        for (int i = 0; i < fields.length; i++) {
454
                                if (!rsmd.getColumnName(i+1).equalsIgnoreCase(geomField))
455
                                {
456
                                        fields[j++] = rsmd.getColumnName(i+1);
457
                                }
458
                        }
459
                        rs.close(); */
460

    
461
                String[] fields = new String[1];
462
                fields[0] = "gid";
463

    
464
                String whereClause = "";
465

    
466
                IVectorialJDBCDriver driver = (IVectorialJDBCDriver) LayerFactory.getDM()
467
                                        .getDriver("PostGIS JDBC Driver");
468

    
469
                // Here you can set the workingArea
470
                // driver.setWorkingArea(dbLayerDefinition.getWorkingArea());
471

    
472

    
473
                String strEPSG = "23030";
474
                DBLayerDefinition lyrDef = new DBLayerDefinition();
475
                lyrDef.setName(layerName);
476
                lyrDef.setTableName(tableName);
477
                lyrDef.setWhereClause(whereClause);
478
                lyrDef.setFieldNames(fields);
479
                lyrDef.setFieldGeometry(geomField);
480
                lyrDef.setFieldID(fidField);
481
                // if (dbLayerDefinition.getWorkingArea() != null)
482
                //     lyrDef.setWorkingArea(dbLayerDefinition.getWorkingArea());
483

    
484
                lyrDef.setSRID_EPSG(strEPSG);
485
                if (driver instanceof ICanReproject)
486
                {
487
                    ((ICanReproject)driver).setDestProjection(strEPSG);
488
                }
489
                driver.setData(conn, lyrDef);
490
                IProjection proj = null;
491
                if (driver instanceof ICanReproject)
492
                {
493
                    proj = CRSFactory.getCRS("EPSG:" + ((ICanReproject)driver).getSourceProjection());
494
                }
495

    
496
                FLayer lyr = LayerFactory.createDBLayer(driver, layerName, proj);
497
                Rectangle2D rectAux = lyr.getFullExtent();
498
                return (FLyrVect) lyr;
499
                }
500
                catch(Exception e)
501
                {
502
                        e.printStackTrace();
503
                }
504
                return null;
505
        }
506
}