Statistics
| Revision:

root / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / drivers / dbf / DbaseFile.java @ 10627

History | View | Annotate | Download (11.5 KB)

1
/*
2
 * Created on 16-feb-2004
3
 *
4
 * To change the template for this generated file go to
5
 * Window>Preferences>Java>Code Generation>Code and Comments
6
 */
7
package com.iver.cit.gvsig.fmap.drivers.dbf;
8

    
9
/**
10
 */
11
import java.io.File;
12
import java.io.FileNotFoundException;
13
import java.io.IOException;
14
import java.io.RandomAccessFile;
15
import java.io.UnsupportedEncodingException;
16
import java.nio.ByteBuffer;
17
import java.nio.channels.FileChannel;
18
import java.nio.charset.Charset;
19
import java.text.FieldPosition;
20
import java.text.NumberFormat;
21
import java.util.Calendar;
22
import java.util.Date;
23
import java.util.Locale;
24

    
25
import com.hardcode.gdbms.driver.exceptions.FileNotFoundDriverException;
26
import com.iver.utiles.bigfile.BigByteBuffer2;
27

    
28
/**
29
 * Class to read and write data to a dbase III format file. Creation date:
30
 * (5/15/2001 5:15:13 PM)
31
 */
32
public class DbaseFile {
33
        // Header information for the DBase File
34
        private DbaseFileHeader myHeader;
35

    
36
        private RandomAccessFile raf;
37

    
38
        private FileChannel channel;
39

    
40
        private BigByteBuffer2 buffer;
41

    
42
        private FileChannel.MapMode mode;
43

    
44
        private FieldFormatter formatter = new FieldFormatter();
45

    
46
        private int posActual = -1;
47

    
48
        private int recordOffset;
49

    
50
        private ByteBuffer cachedRecord = null;
51

    
52
        private byte[] bytesCachedRecord = null;
53

    
54
        private final Number NULL_NUMBER = new Integer(0);
55

    
56
        private final String NULL_STRING = "";
57

    
58
        private final String NULL_DATE = "        ";
59

    
60
        private Charset chars;
61

    
62
        /** Utility for formatting Dbase fields. */
63
        public static class FieldFormatter {
64
                private StringBuffer buffer = new StringBuffer(255);
65

    
66
                private NumberFormat numFormat = NumberFormat
67
                                .getNumberInstance(Locale.US);
68

    
69
                private Calendar calendar = Calendar.getInstance(Locale.US);
70

    
71
                private String emtpyString;
72

    
73
                private static final int MAXCHARS = 255;
74

    
75
                public FieldFormatter() {
76
                        // Avoid grouping on number format
77
                        numFormat.setGroupingUsed(false);
78

    
79
                        // build a 255 white spaces string
80
                        StringBuffer sb = new StringBuffer(MAXCHARS);
81
                        sb.setLength(MAXCHARS);
82
                        for (int i = 0; i < MAXCHARS; i++) {
83
                                sb.setCharAt(i, ' ');
84
                        }
85

    
86
                        emtpyString = sb.toString();
87
                }
88

    
89
                public String getFieldString(int size, String s) {
90
                        buffer.replace(0, size, emtpyString);
91
                        buffer.setLength(size);
92

    
93
                        if (s != null) {
94
                                buffer.replace(0, size, s);
95
                                if (s.length() <= size) {
96
                                        for (int i = s.length(); i < size; i++) {
97
                                                buffer.append(' ');
98
                                        }
99
                                }
100
                        }
101

    
102
                        buffer.setLength(size);
103
                        return buffer.toString();
104
                }
105

    
106
                public String getFieldString(Date d) {
107

    
108
                        if (d != null) {
109
                                buffer.delete(0, buffer.length());
110

    
111
                                calendar.setTime(d);
112
                                int year = calendar.get(Calendar.YEAR);
113
                                int month = calendar.get(Calendar.MONTH) + 1; // returns 0
114
                                                                                                                                // based month?
115
                                int day = calendar.get(Calendar.DAY_OF_MONTH);
116

    
117
                                if (year < 1000) {
118
                                        if (year >= 100) {
119
                                                buffer.append("0");
120
                                        } else if (year >= 10) {
121
                                                buffer.append("00");
122
                                        } else {
123
                                                buffer.append("000");
124
                                        }
125
                                }
126
                                buffer.append(year);
127

    
128
                                if (month < 10) {
129
                                        buffer.append("0");
130
                                }
131
                                buffer.append(month);
132

    
133
                                if (day < 10) {
134
                                        buffer.append("0");
135
                                }
136
                                buffer.append(day);
137
                        } else {
138
                                buffer.setLength(8);
139
                                buffer.replace(0, 8, emtpyString);
140
                        }
141

    
142
                        buffer.setLength(8);
143
                        return buffer.toString();
144
                }
145

    
146
                public String getFieldString(int size, int decimalPlaces, Number n) {
147
                        buffer.delete(0, buffer.length());
148

    
149
                        if (n != null) {
150
                                numFormat.setMaximumFractionDigits(decimalPlaces);
151
                                numFormat.setMinimumFractionDigits(decimalPlaces);
152
                                numFormat.format(n, buffer, new FieldPosition(
153
                                                NumberFormat.INTEGER_FIELD));
154
                        }
155

    
156
                        int diff = size - buffer.length();
157
                        if (diff >= 0) {
158
                                while (diff-- > 0) {
159
                                        buffer.insert(0, ' ');
160
                                }
161
                        } else {
162
                                buffer.setLength(size);
163
                        }
164
                        return buffer.toString();
165
                }
166
        }
167

    
168
        // Retrieve number of records in the DbaseFile
169
        public int getRecordCount() {
170
                return myHeader.getNumRecords();
171
        }
172

    
173
        /**
174
         * DOCUMENT ME!
175
         *
176
         * @return DOCUMENT ME!
177
         */
178
        public int getFieldCount() {
179
                return myHeader.getNumFields();
180
        }
181

    
182
        /**
183
         * DOCUMENT ME!
184
         *
185
         * @param rowIndex
186
         *            DOCUMENT ME!
187
         * @param fieldId
188
         *            DOCUMENT ME!
189
         *
190
         * @return DOCUMENT ME!
191
         */
192
        public boolean getBooleanFieldValue(int rowIndex, int fieldId) {
193
                int recordOffset = (myHeader.getRecordLength() * rowIndex)
194
                                + myHeader.getHeaderLength() + 1;
195

    
196
                // Se calcula el offset del campo
197
                int fieldOffset = 0;
198

    
199
                for (int i = 0; i < (fieldId - 1); i++) {
200
                        fieldOffset += myHeader.getFieldLength(i);
201
                }
202

    
203
                buffer.position(recordOffset + fieldOffset);
204

    
205
                char bool = (char) buffer.get();
206

    
207
                return ((bool == 't') || (bool == 'T') || (bool == 'Y') || (bool == 'y'));
208
        }
209

    
210
        /**
211
         * DOCUMENT ME!
212
         *
213
         * @param rowIndex
214
         *            DOCUMENT ME!
215
         * @param fieldId
216
         *            DOCUMENT ME!
217
         *
218
         * @return DOCUMENT ME!
219
         * @throws UnsupportedEncodingException
220
         */
221
        public String getStringFieldValue(int rowIndex, int fieldId)
222
                        throws UnsupportedEncodingException {
223
                int fieldOffset = myHeader.getFieldDescription(fieldId).myFieldDataAddress;
224
                byte[] data = new byte[myHeader.getFieldLength(fieldId)];
225
                if (rowIndex != posActual) {
226
                        recordOffset = (myHeader.getRecordLength() * rowIndex)
227
                                        + myHeader.getHeaderLength() + 1;
228

    
229
                        /*
230
                         * System.err.println("getStringFieldValue: rowIndex = " +
231
                         * rowIndex); System.err.println("recordOffset = " + recordOffset + "
232
                         * fieldOffset=" + fieldOffset);
233
                         */
234
                        buffer.position(recordOffset);
235
                        buffer.get(bytesCachedRecord);
236
                        cachedRecord = ByteBuffer.wrap(bytesCachedRecord);
237
                        posActual = rowIndex;
238

    
239
                }
240
                cachedRecord.position(fieldOffset);
241
                cachedRecord.get(data);
242

    
243
                return new String(data, chars.name());
244

    
245
        }
246

    
247
        public void setFieldValue(int rowIndex, int fieldId, Object obj)
248
                        throws IOException {
249
                int fieldOffset = myHeader.getFieldDescription(fieldId).myFieldDataAddress;
250
                String str = fieldString(obj, fieldId);
251
                byte[] data = new byte[myHeader.getFieldLength(fieldId)];
252
                recordOffset = (myHeader.getRecordLength() * rowIndex)
253
                                + myHeader.getHeaderLength() + 1;
254

    
255
                ByteBuffer aux = ByteBuffer.wrap(data);
256
                aux.put(str.getBytes(chars.name()));
257
//                raf.seek(recordOffset + fieldOffset);
258
//                raf.writeBytes(str);
259
                aux.flip();
260
                int numBytesWritten = channel.write(aux, recordOffset + fieldOffset);
261
                //channel.force(true);
262

    
263

    
264
        }
265

    
266

    
267
        /**
268
         * Retrieve the name of the given column.
269
         *
270
         * @param inIndex
271
         *            DOCUMENT ME!
272
         *
273
         * @return DOCUMENT ME!
274
         */
275
        public String getFieldName(int inIndex) {
276
                return myHeader.getFieldName(inIndex).trim();
277
        }
278

    
279
        /**
280
         * Retrieve the type of the given column.
281
         *
282
         * @param inIndex
283
         *            DOCUMENT ME!
284
         *
285
         * @return DOCUMENT ME!
286
         */
287
        public char getFieldType(int inIndex) {
288
                return myHeader.getFieldType(inIndex);
289
        }
290

    
291
        /**
292
         * Retrieve the length of the given column.
293
         *
294
         * @param inIndex
295
         *            DOCUMENT ME!
296
         *
297
         * @return DOCUMENT ME!
298
         */
299
        public int getFieldLength(int inIndex) {
300
                return myHeader.getFieldLength(inIndex);
301
        }
302

    
303
        /*
304
         * Retrieve the value of the given column as string.
305
         *
306
         * @param idField DOCUMENT ME! @param idRecord DOCUMENT ME!
307
         *
308
         * @return DOCUMENT ME!
309
         *
310
         * public Object getFieldValue(int idField, long idRecord) throws
311
         * IOException { Object[] tmpReg = getRecord(idRecord); return
312
         * tmpReg[idField]; }
313
         */
314
        /*
315
         * DOCUMENT ME!
316
         *
317
         * @param idField DOCUMENT ME! @param idRecord DOCUMENT ME!
318
         *
319
         * @return DOCUMENT ME!
320
         *
321
         * public double getFieldValueAsDouble(int idField, int idRecord) throws
322
         * IOException { Object[] tmpReg = getRecord(idRecord); return (double)
323
         * Double.parseDouble(tmpReg[idField].toString()); }
324
         */
325

    
326
        /**
327
         * Retrieve the location of the decimal point.
328
         *
329
         * @param inIndex
330
         *            DOCUMENT ME!
331
         *
332
         * @return DOCUMENT ME!
333
         */
334
        public int getFieldDecimalLength(int inIndex) {
335
                return myHeader.getFieldDecimalCount(inIndex);
336
        }
337

    
338
        /**
339
         * read the DBF file into memory.
340
         *
341
         * @param file
342
         *            DOCUMENT ME!
343
         *
344
         * @throws IOException
345
         *             DOCUMENT ME!
346
         */
347
        public void open(File file) throws FileNotFoundDriverException {
348
                /*
349
                 * 01h DOS USA code page 437 02h DOS Multilingual code page 850 03h
350
                 * Windows ANSI code page 1252 04h Standard Macintosh 64h EE MS-DOS code
351
                 * page 852 65h Nordic MS-DOS code page 865 66h Russian MS-DOS code page
352
                 * 866 67h Icelandic MS-DOS 68h Kamenicky (Czech) MS-DOS 69h Mazovia
353
                 * (Polish) MS-DOS 6Ah Greek MS-DOS (437G) 6Bh Turkish MS-DOS 96h
354
                 * Russian Macintosh 97h Eastern European Macintosh 98h Greek Macintosh
355
                 * C8h Windows EE code page 1250 C9h Russian Windows CAh Turkish Windows
356
                 * CBh Greek Windows
357
                 */
358
                try {
359
                if (file.canWrite()) {
360
                        try {
361
                                raf = new RandomAccessFile(file, "rw");
362
                                mode = FileChannel.MapMode.READ_WRITE;
363
                        } catch (FileNotFoundException e) {
364
                                raf = new RandomAccessFile(file, "r");
365
                                mode = FileChannel.MapMode.READ_ONLY;
366
                        }
367
                } else {
368
                        raf = new RandomAccessFile(file, "r");
369
                        mode = FileChannel.MapMode.READ_ONLY;
370
                }
371
                channel = raf.getChannel();
372

    
373
                // buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0,
374
                // channel.size());
375
                buffer = new BigByteBuffer2(channel, mode);
376

    
377
                // create the header to contain the header information.
378
                myHeader = new DbaseFileHeader();
379
                myHeader.readHeader(buffer);
380
                switch (myHeader.getLanguageID()) {
381
                case 0x01:
382
                        chars = Charset.forName("US-ASCII");
383
                        break;
384
                case 0x02:
385
                        chars = Charset.forName("ISO-8859-1");
386
                        break;
387
                case 0x03:
388
                        chars = Charset.forName("windows-1252");
389
                        break;
390
                case 0x04:
391
                        chars = Charset.forName("mac");
392
                        break;
393
                case 0x64:
394
                        chars = Charset.forName("ISO-8859-1");
395
                        break;
396
                case 0x65:
397
                        chars = Charset.forName("ISO-8859-1");
398
                        break;
399
                case 0x66:
400
                        chars = Charset.forName("ISO-8859-1");
401
                        break;
402
                case 0x67:
403
                        chars = Charset.forName("ISO-8859-1");
404
                        break;
405
                case 0x68:
406
                        chars = Charset.forName("greek");
407
                        break;
408
                case 0x69:
409
                        chars = Charset.forName("ISO-8859-1");
410
                        break;
411
                case 0x6A:
412
                        chars = Charset.forName("greek");
413
                        break;
414
                case 0x6B:
415
                        chars = Charset.forName("ISO-8859-1");
416
                        break;
417

    
418
                default:
419
                        chars = Charset.forName("ISO-8859-1");
420
                }
421
                bytesCachedRecord = new byte[myHeader.getRecordLength()];
422
                }catch (IOException e) {
423
                        throw new FileNotFoundDriverException("DBF",e,file.getAbsolutePath());
424
                }
425
        }
426

    
427
        /**
428
         * Removes all data from the dataset
429
         *
430
         * @throws IOException
431
         *             DOCUMENT ME!
432
         */
433
        public void close() throws IOException {
434
                raf.close();
435
                channel.close();
436
                buffer = null;
437
        }
438

    
439
        public FileChannel getWriteChannel() {
440
                return channel;
441
        }
442

    
443
        private String fieldString(Object obj, final int col) {
444
                String o;
445
                final int fieldLen = myHeader.getFieldLength(col);
446
                switch (myHeader.getFieldType(col)) {
447
                case 'C':
448
                case 'c':
449
                        o = formatter.getFieldString(fieldLen, (obj == null) ? NULL_STRING
450
                                        : ((String) obj));
451
                        break;
452
                case 'L':
453
                case 'l':
454
                        o = (obj == null) ? "F"
455
                                        : ((Boolean) obj).booleanValue() == true ? "T" : "F";
456
                        break;
457
                case 'M':
458
                case 'G':
459
                        o = formatter.getFieldString(fieldLen, (obj == null) ? NULL_STRING
460
                                        : ((String) obj));
461
                        break;
462
                case 'N':
463
                case 'n':
464
                case 'F':
465
                case 'f':
466
                        Number number = null;
467
                        if (obj == null) {
468
                                number = NULL_NUMBER;
469
                        } else {
470
                                Number gVal = (Number) obj;
471
                                number = new Double(gVal.doubleValue());
472
                        }
473
                        o = formatter.getFieldString(fieldLen, myHeader
474
                                        .getFieldDecimalCount(col), number);
475
                        break;
476
                case 'D':
477
                case 'd':
478
                        if (obj == null)
479
                                o = NULL_DATE;
480
                        else
481
                                o = formatter.getFieldString(((Date) obj));
482
                        break;
483
                default:
484
                        throw new RuntimeException("Unknown type "
485
                                        + myHeader.getFieldType(col));
486
                }
487

    
488
                return o;
489
        }
490

    
491
}