Statistics
| Revision:

root / branches / v10 / extensions / extOracleSpatial / src / es / prodevelop / cit / gvsig / fmap / drivers / jdbc / oracle / testOracle.java @ 13995

History | View | Annotate | Download (16.7 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2006 Prodevelop and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *   Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *   +34 963862235
28
 *   gvsig@gva.es
29
 *   www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   Prodevelop Integraci?n de Tecnolog?as SL
34
 *   Conde Salvatierra de ?lava , 34-10
35
 *   46004 Valencia
36
 *   Spain
37
 *
38
 *   +34 963 510 612
39
 *   +34 963 510 968
40
 *   gis@prodevelop.es
41
 *   http://www.prodevelop.es
42
 */
43
package es.prodevelop.cit.gvsig.fmap.drivers.jdbc.oracle;
44

    
45
import com.iver.cit.gvsig.fmap.core.GeneralPathX;
46
import com.iver.cit.gvsig.fmap.core.ICanReproject;
47
import com.iver.cit.gvsig.fmap.core.IFeature;
48
import com.iver.cit.gvsig.fmap.core.IGeometry;
49
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
50
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
51
import com.iver.cit.gvsig.fmap.drivers.IFeatureIterator;
52
import com.iver.cit.gvsig.fmap.drivers.WKBParser2;
53

    
54
import com.vividsolutions.jts.geom.MultiLineString;
55
import com.vividsolutions.jts.io.oracle.OraReader;
56

    
57
import oracle.jdbc.driver.OracleDriver;
58
import oracle.jdbc.driver.OracleResultSet;
59

    
60
import oracle.spatial.geometry.JGeometry;
61

    
62
import oracle.sql.ARRAY;
63
import oracle.sql.Datum;
64
import oracle.sql.NUMBER;
65
import oracle.sql.STRUCT;
66

    
67
import org.cresques.cts.IProjection;
68

    
69
import java.awt.geom.PathIterator;
70

    
71
import java.sql.Connection;
72
import java.sql.DriverManager;
73
import java.sql.PreparedStatement;
74
import java.sql.ResultSet;
75
import java.sql.ResultSetMetaData;
76
import java.sql.SQLException;
77
import java.sql.Statement;
78

    
79

    
80
/**
81
 * @author FJP
82
 *
83
 * TODO To change the template for this generated type comment go to Window -
84
 * Preferences - Java - Code Generation - Code and Comments
85
 */
86
public class testOracle {
87
    private static boolean addOrdsToGPX(GeneralPathX gpx, int zero_based_start,
88
        int zero_based_include_end, Datum[] ords, int d, int ltype,
89
        boolean do_the_move, boolean must_do_first) {
90
        int length = ords.length;
91
        boolean return_following_must_do_first = true;
92

    
93
        double x = ((NUMBER) ords[zero_based_start]).doubleValue();
94
        double y = ((NUMBER) ords[zero_based_start + 1]).doubleValue();
95

    
96
        if (must_do_first) {
97
            if (do_the_move) {
98
                gpx.moveTo(x, y);
99
            }
100
            else {
101
                gpx.lineTo(x, y);
102
            }
103
        }
104

    
105
        int ind = 1;
106

    
107
        int size = ((zero_based_include_end - zero_based_start) / d) + 1;
108
        int indx;
109
        int indx2;
110

    
111
        if (ltype == PathIterator.SEG_QUADTO) { // (interpretation = 2)
112

    
113
            double x2;
114
            double y2;
115

    
116
            while (ind < size) {
117
                indx = zero_based_start + (ind * d);
118
                x = ((NUMBER) ords[indx]).doubleValue();
119
                y = ((NUMBER) ords[indx + 1]).doubleValue();
120

    
121
                indx2 = zero_based_start + ((ind + 1) * d);
122

    
123
                if (indx >= length) {
124
                    indx2 = zero_based_start;
125
                }
126

    
127
                x2 = ((NUMBER) ords[indx2]).doubleValue();
128
                y2 = ((NUMBER) ords[indx2 + 1]).doubleValue();
129
                gpx.quadTo(x, y, x2, y2);
130
                ind++;
131
                ind++;
132
            }
133

    
134
            return_following_must_do_first = false;
135
        }
136
        else { // PathIterator.SEG_LINETO (interpretation = 1)
137

    
138
            while (ind < size) {
139
                indx = zero_based_start + (ind * d);
140
                x = ((NUMBER) ords[indx]).doubleValue();
141
                y = ((NUMBER) ords[indx + 1]).doubleValue();
142
                gpx.lineTo(x, y);
143
                ind++;
144
            }
145
        }
146

    
147
        return return_following_must_do_first;
148
    }
149

    
150
    private static int getLineToType(Datum[] infos, int i) {
151
        int resp = PathIterator.SEG_LINETO;
152

    
153
        try {
154
            if (((NUMBER) infos[(3 * i) + 2]).intValue() == 2) {
155
                resp = PathIterator.SEG_QUADTO;
156
            }
157
        }
158
        catch (SQLException e) {
159
            e.printStackTrace();
160
        }
161

    
162
        return resp;
163
    }
164

    
165
    // CREATE TYPE sdo_geometry AS OBJECT (
166
    // SDO_GTYPE NUMBER,
167
    // SDO_SRID NUMBER,
168
    // SDO_POINT SDO_POINT_TYPE,
169
    // SDO_ELEM_INFO SDO_ELEM_INFO_ARRAY,
170
    // SDO_ORDINATES SDO_ORDINATE_ARRAY);
171
    private static GeneralPathX parseOracleStruct(STRUCT s)
172
        throws SQLException {
173
        GeneralPathX resp = new GeneralPathX();
174
        ARRAY infoARRAY = null;
175
        ARRAY ordsARRAY = null;
176
        Datum[] info_array = null;
177
        Datum[] ords_array = null;
178
        int info_array_size = 0;
179
        int[] start_ind;
180
        int[] end_ind;
181
        int dims = 0;
182
        boolean next_must_do_first = true;
183
        Datum[] aux = s.getOracleAttributes();
184

    
185
        infoARRAY = (ARRAY) aux[3];
186
        ordsARRAY = (ARRAY) aux[4];
187

    
188
        dims = ((NUMBER) aux[0]).intValue() / 1000;
189

    
190
        if (dims == 0) {
191
            dims = 2;
192
        }
193

    
194
        info_array = (Datum[]) infoARRAY.getOracleArray();
195
        ords_array = (Datum[]) ordsARRAY.getOracleArray();
196
        info_array_size = info_array.length / 3;
197

    
198
        int last_index = ords_array.length - dims + 1;
199

    
200
        // set indices:
201
        start_ind = new int[info_array_size];
202
        end_ind = new int[info_array_size];
203

    
204
        for (int i = 0; i < info_array_size; i++)
205
            start_ind[i] = ((NUMBER) info_array[3 * i]).intValue();
206

    
207
        for (int i = 0; i < (info_array_size - 1); i++)
208
            end_ind[i] = start_ind[i + 1] - 1;
209

    
210
        end_ind[info_array_size - 1] = last_index;
211

    
212
        int lineType = PathIterator.SEG_LINETO;
213

    
214
        if (end_ind[0] == 0) { // collection of paths
215

    
216
            for (int i = 1; i < info_array_size; i++) {
217
                lineType = getLineToType(info_array, i);
218
                next_must_do_first = addOrdsToGPX(resp, start_ind[i] - 1,
219
                        end_ind[i] - 1, ords_array, dims, lineType, (i == 1),
220
                        next_must_do_first);
221
            }
222
        }
223
        else {
224
            // standard case, do the moveto always
225
            for (int i = 0; i < info_array_size; i++) {
226
                lineType = getLineToType(info_array, i);
227
                addOrdsToGPX(resp, start_ind[i] - 1, end_ind[i] - 1,
228
                    ords_array, dims, lineType, true, true);
229
            }
230
        }
231

    
232
        return resp;
233
    }
234

    
235
    public static void main(String[] args) {
236
        /*
237
         * System.err.println("dburl has the following format:");
238
         * System.err.println("jdbc:postgresql://HOST:PORT/DATABASENAME");
239
         * System.err.println("tablename is 'jdbc_test' by default.");
240
         * System.exit(1);
241
         */
242
        String dburl = "jdbc:oracle:thin:@//localhost:1521/xe";
243
        String dbuser = "system";
244
        String dbpass = "aquilina";
245

    
246
        String dbtable = "VIAS";
247

    
248
        Connection conn = null;
249
        System.out.println("Creating JDBC connection...");
250

    
251
        try {
252
            DriverManager.registerDriver(new OracleDriver());
253

    
254
            conn = DriverManager.getConnection(dburl, dbuser, dbpass);
255

    
256
            conn.setAutoCommit(false);
257

    
258
            long t1 = System.currentTimeMillis();
259
            test1(conn, dburl, dbuser, dbpass, dbtable);
260

    
261
            // testHashID(conn, dburl, dbuser, dbpass, dbtable);
262
            long t2 = System.currentTimeMillis();
263
            System.out.println("Tiempo de consulta1:" + (t2 - t1) +
264
                " milisegundos");
265

    
266
            //                        t1 = System.currentTimeMillis();
267
            //                        OracleSpatialDriver driver = initDriverOracle(conn, dburl, dbuser, dbpass, dbtable);
268
            //                        while (driver.getRowCount() == 0)
269
            //                        {
270
            //                                // do Nothing
271
            //                        }
272
            //                        t2 = System.currentTimeMillis();
273
            //                        System.out.println("Tiempo de inicializar capa:" + (t2 - t1)
274
            //                                        + " milisegundos");
275
            //
276
            //                        t1 = System.currentTimeMillis();
277
            //                        test4(driver);
278
            //                        t2 = System.currentTimeMillis();
279
            //                        System.out.println("Tiempo de recorrer capa:" + (t2 - t1)
280
            //                                        + " milisegundos");
281
            conn.close();
282
        }
283
        catch (SQLException e) {
284
            // TODO Auto-generated catch block
285
            e.printStackTrace();
286
        }
287
    }
288

    
289
    /**
290
     * @param conn
291
     * @param dburl
292
     * @param dbuser
293
     * @param dbpass
294
     * @param dbtable
295
     */
296
    private static void test1(Connection conn, String dburl, String dbuser,
297
        String dbpass, String dbtable) {
298
        try {
299
            String strSQL = "select c.geometry, ROWID from " + dbtable + " c";
300

    
301
            //                        String strSQL = "select c.GEOMETRY, ROWID  from VIAS c where (sdo_filter(GEOMETRY, mdsys.sdo_geometry(2003, 82337, null, mdsys.sdo_elem_info_array(1, 1003, 1), mdsys.sdo_ordinate_array(-167305.445478584,3826564.14408529, 1026816.46891846,3826564.14408529, 1026816.46891846,4919672.72433395, -167305.445478584,4919672.72433395, -167305.445478584,3826564.14408529)), 'mask=anyinteract querytype=window') = 'TRUE')";
302
            Statement s = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
303
                    ResultSet.CONCUR_READ_ONLY);
304
            int fetchSize = 20000;
305
            s.setFetchSize(fetchSize);
306
            s.setFetchDirection(ResultSet.FETCH_FORWARD);
307

    
308
            //            s.execute("declare wkb_cursor binary cursor for " + strSQL);
309
            long t1 = System.currentTimeMillis();
310

    
311
            //            ResultSet r =   s.executeQuery("fetch forward " + fetchSize + " in wkb_cursor");
312
            OracleResultSet r = (OracleResultSet) s.executeQuery(strSQL);
313
            long t2 = System.currentTimeMillis();
314
            System.out.println("Tiempo de consulta:" + (t2 - t1) + " msecs.");
315

    
316
            ResultSetMetaData metadata = r.getMetaData();
317
            System.out.println(metadata.getColumnClassName(1));
318

    
319
            // Estar?a bien tener una clase OraParser separada, 
320
            // igual que tenemos WKBParser y WKTParser.
321
            WKBParser2 parser = new WKBParser2();
322
            int numReg = 0;
323

    
324
            while (r.next()) {
325
                /*
326
                 * ?Hay otros m?todos de leer el campo SDO_GEOMETRY?
327
                 * STRUCT parece muy lento, sobre todo al tener que procesarlo
328
                 * despu?s.
329
                 */
330

    
331
                //                                JGeometry geom = (JGeometry) r.getObject(1, mymap);
332
                //                                byte[] aux2 = r.getBytes(1);
333
                //                                InputStream aux = r.getBinaryStream(1);
334
                STRUCT _st = (oracle.sql.STRUCT) r.getObject(1);
335
                GeneralPathX gpx = parseOracleStruct(_st);
336

    
337
                //                                
338
                //                                // Prueba con la parte de Prodevelop
339
                ////                                GeneralPathX gpx = OracleSpatialUtils.structToGPX(_st
340
                ////                                                .getOracleAttributes());
341
                //                                IGeometry geom = ShapeFactory.createGeometry(new FPolyline2D(gpx));
342

    
343
                /* PRUEBA CON LA CARGA STANDARD DE ORACLE */
344
                //                                 JGeometry jg = JGeometry.load(_st);
345

    
346
                // GeneralPathX gpx = OracleSpatialUtils.structToGPX(_st);
347
                numReg++;
348
            }
349

    
350
            System.out.println("numReg = " + numReg);
351
            s.close();
352
        }
353
        catch (Exception e) {
354
            e.printStackTrace();
355
        }
356
    }
357

    
358
    private static void testHashID(Connection conn, String dburl,
359
        String dbuser, String dbpass, String dbtable) {
360
        try {
361
            /*
362
             * Create a statement and execute a select query.
363
             */
364

    
365
            // String strSQL = "select rowid, c.geometry.SDO_ELEM_INFO from " +
366
            // dbtable + "
367
            // c";
368
            String strSQL = "select rowid from " + dbtable;
369

    
370
            PreparedStatement s = conn.prepareStatement(strSQL);
371

    
372
            // Statement s =
373
            // conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
374
            // ResultSet.CONCUR_READ_ONLY);
375
            int fetchSize = 5000;
376
            s.setFetchSize(fetchSize);
377

    
378
            ResultSet r = s.executeQuery(strSQL);
379
            int id = 0;
380

    
381
            while (r.next()) {
382
                String strAux = r.getString(1);
383
                id++;
384

    
385
                // System.out.println("Row " + id + ":" + strAux);
386
            }
387

    
388
            s.close();
389
        }
390
        catch (Exception e) {
391
            e.printStackTrace();
392
        }
393
    }
394

    
395
    /**
396
     * Prueba con JTS_IO. (OraReader)
397
     * @param conn
398
     * @param dburl
399
     * @param dbuser
400
     * @param dbpass
401
     * @param dbtable
402
     * @throws SQLException
403
     */
404
    private static void test3(Connection conn, String dburl, String dbuser,
405
        String dbpass, String dbtable) throws SQLException {
406
        // Usando el OraReader de JTSIO.
407
        OraReader or = new OraReader();
408

    
409
        String strSQL = "select c.GEOMETRY, ROWID  from VIAS c where (sdo_filter(GEOMETRY, mdsys.sdo_geometry(2003, 82337, null, mdsys.sdo_elem_info_array(1, 1003, 1), mdsys.sdo_ordinate_array(-167305.445478584,3826564.14408529, 1026816.46891846,3826564.14408529, 1026816.46891846,4919672.72433395, -167305.445478584,4919672.72433395, -167305.445478584,3826564.14408529)), 'mask=anyinteract querytype=window') = 'TRUE')";
410

    
411
        Statement s = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
412
                ResultSet.CONCUR_READ_ONLY);
413
        int fetchSize = 20000;
414
        s.setFetchSize(fetchSize);
415
        s.setFetchDirection(ResultSet.FETCH_FORWARD);
416

    
417
        long t1 = System.currentTimeMillis();
418
        ResultSet r = s.executeQuery(strSQL);
419
        long t2 = System.currentTimeMillis();
420
        System.out.println("Tiempo de consulta:" + (t2 - t1) + " msecs.");
421

    
422
        ResultSetMetaData metadata = r.getMetaData();
423
        System.out.println(metadata.getColumnClassName(1));
424

    
425
        WKBParser2 parser = new WKBParser2();
426
        int numReg = 0;
427

    
428
        while (r.next()) {
429
            STRUCT st = (oracle.sql.STRUCT) r.getObject(1);
430
            MultiLineString pt2 = (MultiLineString) or.read(st);
431
            numReg++;
432
        }
433

    
434
        System.out.println("numReg = " + numReg);
435
        s.close();
436
    }
437

    
438
    private static void test4(OracleSpatialDriver driver) {
439
        try {
440
            IFeatureIterator geomIt = driver.getFeatureIterator(
441
                    "SELECT ROWID, GEOMETRY FROM VIAS");
442

    
443
            while (geomIt.hasNext()) {
444
                IFeature feat = geomIt.next();
445
                IGeometry geom = feat.getGeometry();
446
            }
447
        }
448
        catch (Exception e) {
449
            e.printStackTrace();
450
        }
451
    }
452

    
453
    private static OracleSpatialDriver initDriverOracle(Connection conn,
454
        String dburl, String dbuser, String dbpass, String dbtable) {
455
        try {
456
            String fidField = "rowid"; // BE CAREFUL => MAY BE NOT!!!
457
            String geomField = "geometry"; // BE CAREFUL => MAY BE NOT!!! =>
458

    
459
            String[] fields = new String[1];
460
            fields[0] = "rowid";
461

    
462
            String whereClause = "";
463

    
464
            OracleSpatialDriver driver = new OracleSpatialDriver();
465

    
466
            // Here you can set the workingArea
467
            // driver.setWorkingArea(dbLayerDefinition.getWorkingArea());
468
            String strEPSG = "23030";
469
            DBLayerDefinition lyrDef = new DBLayerDefinition();
470
            lyrDef.setName(dbtable);
471
            lyrDef.setTableName(dbtable);
472
            lyrDef.setWhereClause(whereClause);
473
            lyrDef.setFieldNames(fields);
474
            lyrDef.setFieldGeometry(geomField);
475
            lyrDef.setFieldID(fidField);
476

    
477
            // if (dbLayerDefinition.getWorkingArea() != null)
478
            // lyrDef.setWorkingArea(dbLayerDefinition.getWorkingArea());
479
            lyrDef.setSRID_EPSG(strEPSG);
480

    
481
            if (driver instanceof ICanReproject) {
482
                ((ICanReproject) driver).setDestProjection(strEPSG);
483
            }
484

    
485
            driver.setData(conn, lyrDef);
486

    
487
            IProjection proj = null;
488

    
489
            if (driver instanceof ICanReproject) {
490
                proj = CRSFactory.getCRS("EPSG:" +
491
                        ((ICanReproject) driver).getSourceProjection());
492
            }
493

    
494
            return driver;
495
        }
496
        catch (Exception e) {
497
            e.printStackTrace();
498
        }
499

    
500
        return null;
501
    }
502
}