Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.compat.cdc / org.gvsig.fmap.dal / org.gvsig.fmap.dal.file / org.gvsig.fmap.dal.file.dbf / src / main / java / org / gvsig / fmap / dal / store / dbf / utils / DbaseFile.java @ 47467

History | View | Annotate | Download (11.4 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.fmap.dal.store.dbf.utils;
25

    
26
import java.io.File;
27
import java.io.IOException;
28
import java.io.RandomAccessFile;
29
import java.nio.Buffer;
30
import java.nio.ByteBuffer;
31
import java.nio.channels.FileChannel;
32
import java.nio.charset.Charset;
33
import java.util.Date;
34

    
35
import org.gvsig.fmap.dal.exception.CloseException;
36
import org.gvsig.fmap.dal.exception.FileNotFoundException;
37
import org.gvsig.fmap.dal.exception.UnsupportedEncodingException;
38
import org.gvsig.fmap.dal.exception.UnsupportedVersionException;
39
import org.gvsig.fmap.dal.exception.WriteException;
40
import org.gvsig.fmap.dal.feature.exception.AttributeFeatureTypeNotSuportedException;
41
import org.gvsig.utils.bigfile.BigByteBuffer2;
42

    
43
import org.slf4j.Logger;
44
import org.slf4j.LoggerFactory;
45

    
46
/**
47
 * Class to read and write data to a dbase III format file. Creation date:
48
 * (5/15/2001 5:15:13 PM)
49
 */
50
public class DbaseFile {
51

    
52
    private static final Logger logger = LoggerFactory.getLogger(DbaseFile.class);
53

    
54
    public static final int MAX_FIELD_NAME_LENGTH = 10;
55

    
56
    // Header information for the DBase File
57
    private DbaseFileHeader myHeader;
58

    
59
    private File file;
60

    
61
    private RandomAccessFile raf;
62

    
63
    private FileChannel channel;
64

    
65
    private BigByteBuffer2 buffer;
66

    
67
    private FileChannel.MapMode mode;
68

    
69
    private FieldFormatter formatter = new FieldFormatter();
70

    
71
    private long posActual = -1;
72

    
73
    private long recordOffset;
74

    
75
    private ByteBuffer cachedRecord = null;
76

    
77
    private byte[] bytesCachedRecord = null;
78

    
79
    private final Number NULL_NUMBER = 0;
80

    
81
    private final String NULL_STRING = "";
82

    
83
    private final String NULL_DATE = "        ";
84

    
85
    private Charset chars = null;
86
    private Charset charsOriginal;
87

    
88
    private boolean isOpen = false;
89

    
90
    private boolean allowDuplicatedFieldNames;
91

    
92
    public DbaseFile(File afile) {
93
        this(afile, null);
94
    }
95

    
96
    public DbaseFile(File afile, Charset chars) {
97
        this(afile, chars, false);
98
    }
99

    
100
    public DbaseFile(File afile, Charset chars, boolean allowDuplicatedFieldNames) {
101
        this.file = afile;
102
        this.chars = chars;
103
        this.allowDuplicatedFieldNames = allowDuplicatedFieldNames;
104
    }
105

    
106
    public DbaseFileHeader getHeader() {
107
        return myHeader;
108
    }
109
//
110
//    /**
111
//     * @deprecated Use {@link #getCodePageInt()} instead
112
//     */
113
//    @Deprecated
114
//        public byte getCodePage() {
115
//                return (byte) myHeader.getLanguageID();
116
//        }
117

    
118
    public int getCodePageInt() {
119
        return myHeader.getLanguageID();
120
    }
121

    
122
    /**
123
     * Returns the charset used to read/write this dbf. Maybe different from the
124
     * declared in the file if we have forced a different one
125
     */
126
    public String getCharsetName() {
127
        return chars.name();
128
        //return myHeader.getCharsetName();
129
    }
130

    
131
    /**
132
     * Returns the charset declared on the dbf file (or the default one if none
133
     * is declared)
134
     */
135
    public String getOriginalCharsetName() {
136
        return myHeader.getOriginalCharset();
137
    }
138

    
139
    // Retrieve number of records in the DbaseFile
140
    public int getRecordCount() {
141
        return myHeader.getNumRecords();
142
    }
143

    
144
    public int getFieldCount() {
145
        return myHeader.getNumFields();
146
    }
147

    
148
    public boolean getBooleanFieldValue(long rowIndex, int fieldId) {
149
        DbaseFieldDescriptor descriptor = this.myHeader.getFieldDescription(fieldId);
150

    
151
        long recordOffset = (myHeader.getRecordLength() * rowIndex)
152
                + myHeader.getHeaderLength() + 1;
153

    
154
        // Se calcula el offset del campo
155
        int fieldOffset = 0;
156

    
157
        for (int i = 0; i < (fieldId - 1); i++) {
158
            fieldOffset += descriptor.getSize();
159
        }
160

    
161
        buffer.position(recordOffset + fieldOffset);
162

    
163
        char bool = (char) buffer.get();
164

    
165
        return ((bool == 't') || (bool == 'T') || (bool == 'Y') || (bool == 'y'));
166
    }
167

    
168
    public String getStringFieldValue(long rowIndex, int fieldId)
169
            throws UnsupportedEncodingException {
170
        DbaseFieldDescriptor descriptor = this.myHeader.getFieldDescription(fieldId);
171

    
172
        int fieldOffset = descriptor.getOffsetInRecord();
173
        byte[] data = new byte[descriptor.getSize()];
174
        if (rowIndex != posActual) {
175
            recordOffset = (myHeader.getRecordLength() * rowIndex)
176
                    + myHeader.getHeaderLength() + 1;
177

    
178
            /*
179
                         * System.err.println("getStringFieldValue: rowIndex = " +
180
                         * rowIndex); System.err.println("recordOffset = " + recordOffset + "
181
                         * fieldOffset=" + fieldOffset);
182
             */
183
            buffer.position(recordOffset);
184
            buffer.get(bytesCachedRecord);
185
            cachedRecord = ByteBuffer.wrap(bytesCachedRecord);
186
            posActual = rowIndex;
187

    
188
        }
189
        ((Buffer) cachedRecord).position(fieldOffset);
190
        cachedRecord.get(data);
191

    
192
        return new String(data, chars);
193
    }
194

    
195
    public void setFieldValue(long rowIndex, int fieldId, Object obj) throws UnsupportedEncodingException, WriteException {
196
        try {
197
            DbaseFieldDescriptor descriptor = this.myHeader.getFieldDescription(fieldId);
198

    
199
            formatter.setRowIndex(rowIndex);
200
            formatter.setName(descriptor.getName());
201
            int fieldOffset = descriptor.getOffsetInRecord();
202
            String str = fieldString(obj, fieldId);
203
            byte[] data = new byte[descriptor.getSize()];
204
            recordOffset = (myHeader.getRecordLength() * rowIndex)
205
                    + myHeader.getHeaderLength() + 1;
206

    
207
            ByteBuffer aux = ByteBuffer.wrap(data);
208
            aux.put(str.getBytes(chars));
209
//                        raf.seek(recordOffset + fieldOffset);
210
//                        raf.writeBytes(str);
211
            aux.flip();
212
//                        int numBytesWritten = channel.write(aux, recordOffset + fieldOffset);
213
            channel.write(aux, recordOffset + fieldOffset);
214
            //channel.force(true);
215
        } catch (java.io.UnsupportedEncodingException e) {
216
            throw new UnsupportedEncodingException(e);
217
        } catch (IOException e) {
218
            throw new WriteException("DBF", e);
219
        }
220

    
221
    }
222

    
223
    /**
224
     * read the DBF file into memory.
225
     */
226
    public void open() throws FileNotFoundException,
227
            UnsupportedVersionException, IOException, AttributeFeatureTypeNotSuportedException {
228

    
229
        if (!file.exists()) {
230
            throw new FileNotFoundException(file);
231
        }
232
//                if (file.canWrite()) {
233
//                        try {
234
//                                raf = new RandomAccessFile(file, "rw");
235
//                                mode = FileChannel.MapMode.READ_WRITE;
236
//                        } catch (java.io.FileNotFoundException e) {
237
//                                raf = new RandomAccessFile(file, "r");
238
//                                mode = FileChannel.MapMode.READ_ONLY;
239
//                        }
240
//                } else {
241
        raf = new RandomAccessFile(file, "r");
242
        mode = FileChannel.MapMode.READ_ONLY;
243
//                }
244
        channel = raf.getChannel();
245

    
246
        // buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0,
247
        // channel.size());
248
        buffer = new BigByteBuffer2(channel, mode);
249

    
250
        // create the header to contain the header information.
251
        myHeader = new DbaseFileHeader();
252
        if (chars == null) {
253
            myHeader.read(buffer, null, allowDuplicatedFieldNames);
254
        } else {
255
            myHeader.read(buffer, chars.name(), allowDuplicatedFieldNames);
256
        }
257
        if (myHeader.getLanguageID() == 0x00) {
258
            // read from the .cpg file if ldid is 0x00
259
            DbaseCodepage cpReader = new DbaseCodepage(file);
260
            String charsetName = cpReader.read();
261
            if (charsetName == null) {
262
                charsetName = "ISO-8859-1"; // for compatibility with old gvSIG files
263
            }
264
            charsOriginal = Charset.forName(myHeader.mappingEncoding(charsetName));
265
        } else {
266
            charsOriginal = Charset.forName(myHeader.mappingEncoding(myHeader.getOriginalCharset()));
267
        }
268
        if (chars == null) {
269
            chars = charsOriginal;
270
        }
271
        bytesCachedRecord = new byte[myHeader.getRecordLength()];
272
        this.isOpen = true;
273
    }
274

    
275
    /**
276
     * Removes all data from the dataset
277
     */
278
    public void close() throws CloseException {
279
        logger.debug("Closing dbf file '" + this.file.getAbsolutePath() + "'");
280

    
281
        try {
282
            raf.close();
283
            channel.close();
284
            buffer = null;
285
            posActual = -1;
286
            myHeader = null;
287
        } catch (Exception e) {
288
            throw new CloseException("DBF", e);
289
        }
290
        this.isOpen = false;
291
    }
292

    
293
    public FileChannel getWriteChannel() {
294
        return channel;
295
    }
296

    
297
    private String fieldString(Object obj, final int col) {
298
        DbaseFieldDescriptor descriptor = this.myHeader.getFieldDescription(col);
299

    
300
        String o;
301
        final int fieldLen = descriptor.getSize();
302
        switch (descriptor.getType()) {
303
            case 'C':
304
            case 'c':
305
                o = formatter.format(
306
                        (obj == null) ? NULL_STRING : ((String) obj),
307
                        fieldLen
308
                );
309
                break;
310
            case 'L':
311
            case 'l':
312
                o = (obj == null) ? "F" : ((Boolean) obj) == true ? "T" : "F";
313
                break;
314
            case 'M':
315
            case 'G':
316
                o = formatter.format(
317
                        (obj == null) ? NULL_STRING : (String) obj,
318
                        fieldLen
319
                );
320
                break;
321
            case 'N':
322
            case 'n':
323
            case 'F':
324
            case 'f':
325
                Number number;
326
                if (obj == null) {
327
                    number = NULL_NUMBER;
328
                } else {
329
                    Number gVal = (Number) obj;
330
                    number = gVal.doubleValue();
331
                }
332
                o = formatter.format(
333
                        (double) number,
334
                        fieldLen,
335
                        descriptor.getScale()
336
                );
337
                break;
338
            case 'D':
339
            case 'd':
340
                if (obj == null) {
341
                    o = NULL_DATE;
342
                } else {
343
                    o = formatter.formatDate(((Date) obj));
344
                }
345
                break;
346
            default:
347
                throw new RuntimeException("Unknown type " + descriptor.getType());
348
        }
349
        return o;
350
    }
351

    
352
    public boolean isOpen() {
353
        return this.isOpen;
354
    }
355

    
356
    public int getFieldIndex(String name) {
357
        return myHeader.getFieldIndex(name);
358
    }
359

    
360
    public Charset getCurrenCharset() {
361
        return chars;
362
    }
363

    
364
    public Charset getOriginalCharset() {
365
        return charsOriginal;
366
    }
367

    
368
    public void setCharset(Charset chars) {
369
        this.chars = chars;
370
    }
371

    
372
    public boolean isWritable() {
373
        return this.file.canWrite();
374
    }
375

    
376
}