Statistics
| Revision:

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

History | View | Annotate | Download (7.12 KB)

1
/*
2
 * Created on 11-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.sql.Connection;
47
import java.sql.ResultSet;
48
import java.sql.ResultSetMetaData;
49
import java.sql.SQLException;
50
import java.sql.Statement;
51

    
52
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
53
import com.hardcode.gdbms.engine.values.Value;
54
import com.iver.cit.gvsig.fmap.core.DefaultFeature;
55
import com.iver.cit.gvsig.fmap.core.IFeature;
56
import com.iver.cit.gvsig.fmap.core.IGeometry;
57
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
58
import com.iver.cit.gvsig.fmap.drivers.IFeatureIterator;
59
import com.iver.cit.gvsig.fmap.drivers.WKBParser2;
60
import com.iver.cit.gvsig.fmap.drivers.WKBParser3;
61
import com.iver.cit.gvsig.fmap.drivers.XTypes;
62

    
63
/**
64
 * @author FJP
65
 *
66
 * TODO To change the template for this generated type comment go to Window -
67
 * Preferences - Java - Code Generation - Code and Comments
68
 */
69
public class PostGisFeatureIterator implements IFeatureIterator {
70
        private static int FETCH_SIZE = 5000;
71

    
72
        private WKBParser3 parser = new WKBParser3();
73

    
74
        private ResultSetMetaData metaData = null;
75

    
76
        ResultSet rs;
77

    
78
        Statement st;
79

    
80
        String strAux;
81

    
82
        IGeometry geom;
83

    
84
        int numColumns;
85

    
86
        Value[] regAtt;
87

    
88
        /**
89
         * Array con la correspondencia entre un campo de la consulta y el campo
90
         * dentro de regAtt
91
         */
92
        int[] relIds;
93

    
94
        private DBLayerDefinition lyrDef;
95

    
96
        int numReg = 0;
97

    
98
        int idFieldID = -1;
99

    
100
        String cursorName;
101

    
102
        /**
103
         * @throws SQLException
104
         * @throws SQLException
105
         *
106
         */
107
        public PostGisFeatureIterator(Connection conn, String cursorName, String sql)
108
                        throws SQLException {
109

    
110
                // Basado en 0, es decir, no cuenta el campo
111
                // de geometria
112
                // Debe ser forward only
113
                st = conn.createStatement();
114
                
115
                // CodeSprint 2010 (Manuel L?pez S?nchez)
116
                try{
117
                        st.execute("BEGIN");  
118
                }catch(SQLException e){
119
                        st.execute("END"); // Cerramos la transacci?n para anular los cursores binarios
120
                                                                        // que pueden quedar colgados (from CodeSprint 2010)                                                                
121
                        st.execute("BEGIN"); // Si salta otra excepci?n, no la capturamos
122
                }
123
                // End CodeSprint 2010
124
                st.execute("declare " + cursorName + " binary cursor for " + sql);
125

    
126
                this.rs = st.executeQuery("fetch forward " + FETCH_SIZE + " in "
127
                                + cursorName);
128

    
129
                this.cursorName = cursorName;
130
                numColumns = rs.getMetaData().getColumnCount();
131
                metaData = rs.getMetaData();
132
                numReg = 0;
133

    
134
        }
135

    
136
        /*
137
         * (non-Javadoc)
138
         *
139
         * @see com.iver.cit.gvsig.fmap.drivers.jdbc.GeometryIterator#hasNext()
140
         */
141
        public boolean hasNext() throws ReadDriverException {
142
                try {
143
                        if (numReg > 0)
144
                                if ((numReg % FETCH_SIZE) == 0) {
145
                                        rs = st.executeQuery("fetch forward " + FETCH_SIZE + " in "
146
                                                        + cursorName);
147
                                        // System.out.println("ejecutando la query otra vez");
148
                                }
149
                        // System.out.println("hasNext con numReg=" + numReg);
150
                        if (rs.next())
151
                                return true;
152
                        else {
153
                                closeIterator();
154
                                return false;
155
                        }
156
                } catch (SQLException e) {
157
//                        SqlDriveExceptionType type = new SqlDriveExceptionType();
158
//            type.setDriverName("PostGIS Driver");
159
//            try {
160
//                                type.setSql(rs.getStatement().toString());
161
//                        } catch (SQLException e1) {
162
//                                e1.printStackTrace();
163
//                        }
164
            throw new ReadDriverException("PostGIS Driver",e);
165
//                        throw new DriverException(e);
166
                }
167

    
168
        }
169

    
170
        /*
171
         * (non-Javadoc)
172
         *
173
         * @see com.iver.cit.gvsig.fmap.drivers.jdbc.GeometryIterator#next()
174
         */
175
        public IFeature next() throws ReadDriverException {
176
                byte[] data;
177
                try {
178
                        data = rs.getBytes(1);
179
                        geom = parser.parse(data);
180
                        for (int fieldId = 2; fieldId <= numColumns; fieldId++) {
181
                                Value val = PostGisDriver.getFieldValue(rs, fieldId);
182
                                regAtt[relIds[fieldId - 2]] = val;
183
                        }
184

    
185
                        // TODO: Aqu? habr?a que usar una Factor?a.
186
                        IFeature feat = null;
187
                        if (idFieldID != -1) {
188
                                String theID = regAtt[lyrDef.getIdFieldID()].toString();
189
                                feat = new DefaultFeature(geom, regAtt.clone(), theID);
190
                        }
191
                        else
192
                        {
193
//                                // feat = new DefaultFeature(geom, regAtt);
194
//                                FeatureWithoutIdExceptionType  type = new FeatureWithoutIdExceptionType();
195
//                        type.setSchema(lyrDef);
196
                                throw new ReadDriverException("PostGIS Driver",null);
197
                        }
198
                        numReg++;
199
                        return feat;
200
                } catch (SQLException e) {
201
//                        SqlDriveExceptionType type = new SqlDriveExceptionType();
202
//            type.setDriverName("PostGIS Driver");
203
//            try {
204
//                                type.setSql(rs.getStatement().toString());
205
//                        } catch (SQLException e1) {
206
//                                e1.printStackTrace();
207
//                        }
208
            throw new ReadDriverException("PostGIS Driver",e);
209
//                        throw new DriverException(e);
210
                }
211

    
212
        }
213

    
214

    
215
        /*
216
         * (non-Javadoc)
217
         *
218
         * @see com.iver.cit.gvsig.fmap.drivers.IFeatureIterator#closeIterator()
219
         */
220
        public void closeIterator() throws ReadDriverException {
221
                try {
222
                        numReg = 0;
223

    
224
                        // st.execute("CLOSE " + cursorName);
225
                        // st.execute("COMMIT");
226
                        rs.close();
227
                } catch (SQLException e) {
228
//                        SqlDriveExceptionType type = new SqlDriveExceptionType();
229
//            type.setDriverName("PostGIS Driver");
230
//            try {
231
//                                type.setSql(rs.getStatement().toString());
232
//                        } catch (SQLException e1) {
233
//                                e1.printStackTrace();
234
//                        }
235
            throw new ReadDriverException("PostGIS Driver",e);
236
//                        throw new DriverException(e);
237
                }
238
                // st.execute("COMMIT");
239
                // st.close();
240

    
241
        }
242

    
243
        public void setLyrDef(DBLayerDefinition lyrDef) {
244
                this.lyrDef = lyrDef;
245
                // Aunque no nos hayan pedido todos los campos, devolveremos
246
                // tantos atributos como la capa tiene. Eso s?, puestos a null
247
                regAtt = new Value[lyrDef.getFieldNames().length];
248
                relIds = new int[numColumns - 1];
249

    
250
                try {
251
                        for (int i = 2; i <= metaData.getColumnCount(); i++) {
252
                                int idRel = lyrDef.getFieldIdByName(metaData.getColumnName(i));
253
                                if (idRel == -1)
254
                                {
255
                                        throw new RuntimeException("No se ha encontrado el nombre de campo " + metaData.getColumnName(i));
256
                                }
257
                                relIds[i - 2] = idRel;
258
                                if (lyrDef.getFieldID().equals(metaData.getColumnName(i))) {
259
                                        idFieldID = i;
260
                                        // break;
261
                                }
262
                        }
263
                } catch (SQLException e) {
264
                        // Si no est?, no pasa nada
265
                        e.printStackTrace();
266
                }
267

    
268
        }
269

    
270
}