Statistics
| Revision:

root / branches / v2_0_0_prep / libraries / libFMap_dalfile / src / org / gvsig / fmap / dal / store / shp / utils / SHPFileWrite.java @ 34899

History | View | Annotate | Download (9.64 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 IVER T.I. 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
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package org.gvsig.fmap.dal.store.shp.utils;
42

    
43
import java.io.IOException;
44
import java.nio.ByteBuffer;
45
import java.nio.ByteOrder;
46
import java.nio.channels.FileChannel;
47

    
48
import org.gvsig.fmap.dal.exception.WriteException;
49
import org.gvsig.fmap.geom.Geometry;
50
import org.gvsig.fmap.geom.GeometryLocator;
51
import org.gvsig.fmap.geom.GeometryManager;
52
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
53
import org.gvsig.fmap.geom.exception.CreateEnvelopeException;
54
import org.gvsig.fmap.geom.primitive.Envelope;
55
import org.slf4j.Logger;
56
import org.slf4j.LoggerFactory;
57

    
58

    
59

    
60
/**
61
 * DOCUMENT ME!
62
 *
63
 * @author Vicente Caballero Navarro
64
 */
65
public class SHPFileWrite {
66
        private static final GeometryManager geomManager = GeometryLocator.getGeometryManager();
67
        private static final Logger logger = LoggerFactory.getLogger(SHPFileWrite.class);
68
        private SHPShape m_shape = null;
69
        private ByteBuffer m_bb = null;
70
        private ByteBuffer m_indexBuffer = null;
71
        private int m_pos = 0;
72
        private int m_offset;
73
        //        private int m_type;
74
        private int m_cnt;
75
        private FileChannel shpChannel;
76
        private FileChannel shxChannel;
77
//        private double flatness;
78

    
79
        /**
80
         * Crea un nuevo SHPFileWrite.
81
         *
82
         * @param shpChannel DOCUMENT ME!
83
         * @param shxChannel DOCUMENT ME!
84
         */
85
        public SHPFileWrite(FileChannel shpChannel, FileChannel shxChannel) {
86
                this.shpChannel = shpChannel;
87
                this.shxChannel = shxChannel;
88
        }
89

    
90
        /**
91
         * Make sure our buffer is of size.
92
         *
93
         * @param size DOCUMENT ME!
94
         */
95
        private void checkShapeBuffer(int size) {
96
                if (m_bb.capacity() < size) {
97
                        m_bb = ByteBuffer.allocateDirect(size);
98
                }
99
        }
100

    
101
        /**
102
         * Drain internal buffers into underlying channels.
103
         * @throws WriteException
104
         *
105
         * @throws IOException DOCUMENT ME!
106
         */
107
        private void drain() throws WriteException {
108
                m_bb.flip();
109
                m_indexBuffer.flip();
110
                try{
111
                while (m_bb.remaining() > 0) {
112
                        shpChannel.write(m_bb);
113
                }
114

    
115
                while (m_indexBuffer.remaining() > 0) {
116
                        shxChannel.write(m_indexBuffer);
117
                }
118
                }catch (IOException e) {
119
                        throw new WriteException("SHP File Write Drain", e);
120
                }
121
                m_bb.flip().limit(m_bb.capacity());
122
                m_indexBuffer.flip().limit(m_indexBuffer.capacity());
123
        }
124

    
125
        /**
126
         * DOCUMENT ME!
127
         */
128
        private void allocateBuffers() {
129
                m_bb = ByteBuffer.allocateDirect(16 * 1024);
130
                m_indexBuffer = ByteBuffer.allocateDirect(100);
131
        }
132

    
133
        /**
134
         * Close the underlying Channels.
135
         */
136
        public void close() throws WriteException {
137
                try {
138
                        shpChannel.close();
139
                        shxChannel.close();
140
                } catch (IOException e) {
141
                        throw new WriteException("SHP File Write Close", e);
142
                }
143
                shpChannel = null;
144
                shxChannel = null;
145
                m_shape = null;
146

    
147
                if (m_indexBuffer instanceof ByteBuffer) {
148
                        if (m_indexBuffer != null) {
149
                                ///NIOUtilities.clean(m_indexBuffer);
150
                        }
151
                }
152

    
153
                if (m_indexBuffer instanceof ByteBuffer) {
154
                        if (m_indexBuffer != null) {
155
                                ///NIOUtilities.clean(m_bb);
156
                        }
157
                }
158

    
159
                m_indexBuffer = null;
160
                m_bb = null;
161
        }
162

    
163
        /**
164
         * DOCUMENT ME!
165
         *
166
         * @param geometries DOCUMENT ME!
167
         * @param type DOCUMENT ME!
168
         *
169
         */
170
        public void write(Geometry[] geometries, int type)
171
                        throws WriteException {
172
                m_shape = SHP.create(type);
173
//                m_shape.setFlatness(flatness);
174
                writeHeaders(geometries, type);
175

    
176
                m_pos = m_bb.position();
177

    
178
                for (int i = 0, ii = geometries.length; i < ii; i++) {
179
                        writeGeometry(geometries[i]);
180
                }
181

    
182
                close();
183
        }
184

    
185
        /**
186
         * DOCUMENT ME!
187
         *
188
         * @param geometries DOCUMENT ME!
189
         * @param type DOCUMENT ME!
190
         * @throws WriteException
191
         *
192
         */
193
        private void writeHeaders(Geometry[] geometries, int type)
194
                        throws WriteException {
195
                int fileLength = 100;
196
                Envelope extent = null;
197

    
198
                for (int i = geometries.length - 1; i >= 0; i--) {
199
                        Geometry fgeometry = geometries[i];
200
                        m_shape.obtainsPoints(fgeometry);
201
                        int size = m_shape.getLength(fgeometry) + 8;
202
                        fileLength += size;
203

    
204
                        if (extent == null) {
205
                                try {
206
                                        extent = geomManager.createEnvelope(SUBTYPES.GEOM2D);
207
                                } catch (CreateEnvelopeException e) {
208
                                        logger.error("Error creating the envelope", e);
209
                                }
210
                        } else {
211
                                extent.add(fgeometry.getEnvelope());
212
                        }
213
                }
214

    
215
                writeHeaders(extent, type, geometries.length, fileLength);
216
        }
217

    
218
        /**
219
         * Writes shape header (100 bytes)
220
         *
221
         * @param bounds DOCUMENT ME!
222
         * @param type DOCUMENT ME!
223
         * @param numberOfGeometries DOCUMENT ME!
224
         * @param fileLength DOCUMENT ME!
225
         */
226
        public void writeHeaders(Envelope bounds, int type,
227
                int numberOfGeometries,
228
                        int fileLength) throws WriteException {
229
                /*try {
230
                   handler = type.getShapeHandler();
231
                   } catch (ShapefileException se) {
232
                     throw new RuntimeException("unexpected Exception",se);
233
                   }
234
                 */
235
                if (m_bb == null) {
236
                        allocateBuffers();
237
                }
238
                // Posicionamos al principio.
239
                m_bb.position(0);
240
                m_indexBuffer.position(0);
241

    
242
                ShapeFileHeader2 header = new ShapeFileHeader2();
243

    
244
                header.write(m_bb, type, numberOfGeometries, fileLength / 2,
245
                        bounds
246
                                .getMinimum(0), bounds.getMinimum(1), bounds.getMaximum(0),
247
                        bounds.getMaximum(1), 0, 0, 0, 0);
248

    
249
                header.write(m_indexBuffer, type, numberOfGeometries,
250
                        50 + (4 * numberOfGeometries), bounds.getMinimum(0), bounds.getMinimum(1),
251
                        bounds.getMaximum(0), bounds.getMaximum(1), 0, 0, 0, 0);
252

    
253
                m_offset = 50;
254
//                m_type = type;
255
                m_cnt = 0;
256

    
257
                try {
258
                        shpChannel.position(0);
259
                        shxChannel.position(0);
260
                } catch (IOException e) {
261
                        throw new WriteException("SHP File Write Headers", e);
262
                }
263
                drain();
264
        }
265
        public int writeIGeometry(Geometry g) throws WriteException {
266
                int shapeType = getShapeType(g.getType(), g.getGeometryType().getSubType());
267
                m_shape = SHP.create(shapeType);
268
//                m_shape.setFlatness(flatness);
269
                // System.out.println("writeIGeometry: type="+ g.getType());
270
                return writeGeometry(g);
271
        }
272

    
273
        /**
274
         * Writes a single Geometry.
275
         *
276
         * @param g
277
         * @return the position of buffer (after the last geometry, it will allow you to
278
         * write the file size in the header.
279
         */
280
        public synchronized int writeGeometry(Geometry g)
281
                        throws WriteException {
282
                if (m_bb == null) {
283
                        allocateBuffers();
284
                        m_offset = 50;
285
                        m_cnt = 0;
286

    
287
                        try {
288
                                shpChannel.position(0);
289
                                shxChannel.position(0);
290
                        } catch (IOException e) {
291
                                throw new WriteException("SHP File Write", e);
292
                        }
293
                        // throw new IOException("Must write headers first");
294
                }
295

    
296
                m_pos = m_bb.position();
297
                m_shape.obtainsPoints(g);
298
                int length = m_shape.getLength(g);
299

    
300
                // must allocate enough for shape + header (2 ints)
301
                checkShapeBuffer(length + 8);
302

    
303
                length /= 2;
304

    
305
                m_bb.order(ByteOrder.BIG_ENDIAN);
306
                m_bb.putInt(++m_cnt);
307
                m_bb.putInt(length);
308
                m_bb.order(ByteOrder.LITTLE_ENDIAN);
309
                m_bb.putInt(m_shape.getShapeType());
310
                m_shape.write(m_bb, g);
311

    
312
                ///assert (length * 2 == (m_bb.position() - m_pos) - 8);
313
                m_pos = m_bb.position();
314

    
315
                // write to the shx
316
                m_indexBuffer.putInt(m_offset);
317
                m_indexBuffer.putInt(length);
318
                m_offset += (length + 4);
319
                drain();
320

    
321
                ///assert(m_bb.position() == 0);
322
                return m_pos; // Devolvemos hasta donde hemos escrito
323
        }
324

    
325
        /**
326
         * Returns a shapeType compatible with shapeFile constants from a gvSIG's IGeometry type
327
         * @param geometryType
328
         * @return a shapeType compatible with shapeFile constants from a gvSIG's IGeometry type
329
         */
330
        public int getShapeType(int geometryType, int geometrySubType) {
331

    
332
                if (geometrySubType == Geometry.SUBTYPES.GEOM3D){
333
                        switch (geometryType) {
334
                        case Geometry.TYPES.POINT:
335
                                return SHP.POINT3D;
336

    
337
                        case Geometry.TYPES.CURVE:
338
                        case Geometry.TYPES.MULTICURVE:
339
                        case Geometry.TYPES.ELLIPSE:
340
                        case Geometry.TYPES.CIRCLE:
341
                        case Geometry.TYPES.ARC:
342
                                return SHP.POLYLINE3D;
343

    
344
                        case Geometry.TYPES.SURFACE:
345
                        case Geometry.TYPES.MULTISURFACE:
346
                                return SHP.POLYGON3D;
347

    
348
                        case Geometry.TYPES.MULTIPOINT:
349
                                return SHP.MULTIPOINT3D; //TODO falta aclarar cosas aqu?.
350
                }
351

    
352
                }else{
353
                        switch (geometryType) {
354
                                case Geometry.TYPES.POINT:
355
                                        return SHP.POINT2D;
356

    
357
                                case Geometry.TYPES.CURVE:
358
                                case Geometry.TYPES.MULTICURVE:
359
                                case Geometry.TYPES.ELLIPSE:
360
                                case Geometry.TYPES.CIRCLE:
361
                                case Geometry.TYPES.ARC:
362
                                        return SHP.POLYLINE2D;
363

    
364
                                case Geometry.TYPES.SURFACE:
365
                                case Geometry.TYPES.MULTISURFACE:
366
                                        return SHP.POLYGON2D;
367

    
368
                                case Geometry.TYPES.MULTIPOINT:
369
                                        return SHP.MULTIPOINT2D; //TODO falta aclarar cosas aqu?.
370
                        }
371
                }
372
                        return SHP.NULL;
373
                }
374

    
375
//        public void setFlatness(double flatness) {
376
//                this.flatness=flatness;
377
//        }
378

    
379
}