Statistics
| Revision:

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

History | View | Annotate | Download (6.78 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.WKBParser3;
60

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

    
70
        private WKBParser3 parser = new WKBParser3();
71

    
72
        private ResultSetMetaData metaData = null;
73

    
74
        ResultSet rs;
75

    
76
        Statement st;
77

    
78
        String strAux;
79

    
80
        IGeometry geom;
81

    
82
        int numColumns;
83

    
84
        Value[] regAtt;
85

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

    
92
        private DBLayerDefinition lyrDef;
93

    
94
        int numReg = 0;
95

    
96
        int idFieldID = -1;
97

    
98
        String cursorName;
99

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

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

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

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

    
132
        }
133

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

    
166
        }
167

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

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

    
210
        }
211

    
212

    
213
        /*
214
         * (non-Javadoc)
215
         *
216
         * @see com.iver.cit.gvsig.fmap.drivers.IFeatureIterator#closeIterator()
217
         */
218
    public void closeIterator() throws ReadDriverException {
219
        try {
220
            numReg = 0;
221
            // st.execute("CLOSE " + cursorName); fpuga: Not need as we are
222
            // using non-holdable cursor
223
            st.execute("COMMIT");
224
            rs.close();
225
            st.close();
226
        } catch (SQLException e) {
227
            throw new ReadDriverException("PostGIS Driver", e);
228
        }
229
    }
230

    
231
        public void setLyrDef(DBLayerDefinition lyrDef) {
232
                this.lyrDef = lyrDef;
233
                // Aunque no nos hayan pedido todos los campos, devolveremos
234
                // tantos atributos como la capa tiene. Eso s?, puestos a null
235
                regAtt = new Value[lyrDef.getFieldNames().length];
236
                relIds = new int[numColumns - 1];
237

    
238
                try {
239
                        for (int i = 2; i <= metaData.getColumnCount(); i++) {
240
                                int idRel = lyrDef.getFieldIdByName(metaData.getColumnName(i));
241
                                if (idRel == -1)
242
                                {
243
                                        throw new RuntimeException("No se ha encontrado el nombre de campo " + metaData.getColumnName(i));
244
                                }
245
                                relIds[i - 2] = idRel;
246
                                if (lyrDef.getFieldID().equals(metaData.getColumnName(i))) {
247
                                        idFieldID = i;
248
                                        // break;
249
                                }
250
                        }
251
                } catch (SQLException e) {
252
                        // Si no est?, no pasa nada
253
                        e.printStackTrace();
254
                }
255

    
256
        }
257

    
258
}