Statistics
| Revision:

svn-gvsig-desktop / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / drivers / dbf / DBFDriver.java @ 6356

History | View | Annotate | Download (11.4 KB)

1
package com.iver.cit.gvsig.fmap.drivers.dbf;
2

    
3
import java.io.File;
4
import java.io.FileInputStream;
5
import java.io.FileNotFoundException;
6
import java.io.FileOutputStream;
7
import java.io.IOException;
8
import java.io.RandomAccessFile;
9
import java.nio.channels.FileChannel;
10
import java.nio.channels.WritableByteChannel;
11
import java.sql.Types;
12
import java.text.DateFormat;
13
import java.text.ParseException;
14
import java.util.Date;
15
import java.util.Locale;
16
import java.util.Properties;
17

    
18
import com.hardcode.gdbms.driver.DriverUtilities;
19
import com.hardcode.gdbms.engine.data.DataSourceFactory;
20
import com.hardcode.gdbms.engine.data.driver.DriverException;
21
import com.hardcode.gdbms.engine.data.driver.FileDriver;
22
import com.hardcode.gdbms.engine.data.edition.DataWare;
23
import com.hardcode.gdbms.engine.data.file.FileDataWare;
24
import com.hardcode.gdbms.engine.values.Value;
25
import com.hardcode.gdbms.engine.values.ValueFactory;
26
import com.iver.cit.gvsig.fmap.drivers.ITableDefinition;
27
import com.iver.cit.gvsig.fmap.drivers.shp.DbaseFileHeaderNIO;
28
import com.iver.cit.gvsig.fmap.drivers.shp.DbaseFileWriterNIO;
29
import com.iver.cit.gvsig.fmap.edition.EditionException;
30
import com.iver.cit.gvsig.fmap.edition.IRowEdited;
31
import com.iver.cit.gvsig.fmap.edition.IWriteable;
32
import com.iver.cit.gvsig.fmap.edition.IWriter;
33
import com.iver.cit.gvsig.fmap.edition.writers.dbf.DbfWriter;
34

    
35

    
36
/**
37
 * DOCUMENT ME!
38
 *
39
 * @author Fernando Gonz?lez Cort?s
40
 */
41
public class DBFDriver implements FileDriver, IWriteable, IWriter {
42
    //private File file;
43
    private static Locale ukLocale = new Locale("en", "UK"); // English, UK version
44
    private DbaseFile dbf = new DbaseFile();
45
    private char[] fieldTypes;
46
    private DataSourceFactory dsf;
47
    private DbfWriter dbfWriter = new DbfWriter();
48
        private File file = null;
49
        private static String tempDirectoryPath = System.getProperty("java.io.tmpdir");
50
        private File fTemp;
51

    
52

    
53
    /**
54
     * @see com.hardcode.driverManager.Driver#getName()
55
     */
56
    public String getName() {
57
        return "gdbms dbf driver";
58
    }
59

    
60
    /**
61
     * @see com.hardcode.gdbms.engine.data.GDBMSDriver#open(java.io.File)
62
     */
63
    public void open(File file) throws IOException {
64
            this.file  = file;
65
        dbf.open(file);
66

    
67
        try {
68
            fieldTypes = new char[getFieldCount()];
69

    
70
            for (int i = 0; i < fieldTypes.length; i++) {
71
                fieldTypes[i] = dbf.getFieldType(i);
72
            }
73
//            dbfWriter.setFile(file);
74
        } catch (DriverException e) {
75
            throw new IOException(e.getMessage());
76
        }
77

    
78
    }
79

    
80
    /**
81
     * @see com.hardcode.gdbms.engine.data.GDBMSDriver#close()
82
     */
83
    public void close() throws IOException {
84
        dbf.close();
85
    }
86

    
87
    /**
88
     * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldValue(long,
89
     *      int)
90
     */
91
    public Value getFieldValue(long rowIndex, int fieldId)
92
        throws DriverException {
93
        // Field Type (C  or M)
94
        char fieldType = fieldTypes[fieldId];
95

    
96
        if (fieldType == 'L') {
97
            return ValueFactory.createValue(dbf.getBooleanFieldValue(
98
                    (int) rowIndex, fieldId));
99

    
100
            /*                }else if (fieldType == 'N'){
101
               String strValue = dbf.getStringFieldValue(rowIndex, fieldId);
102
               long value = Long.parseLong(strValue);
103
               if ((value > Integer.MIN_VALUE) && (value < Integer.MAX_VALUE)){
104
                       return new IntValue((int) value);
105
               }else{
106
                       return new LongValue(value);
107
               }
108
             */
109
        } else if ((fieldType == 'F') || (fieldType == 'N')) {
110
            String strValue = dbf.getStringFieldValue((int) rowIndex, fieldId)
111
                                 .trim();
112

    
113
            if (strValue.length() == 0) {
114
                return null;
115
            }
116
            double value=0;
117
            try{
118
            value = Double.parseDouble(strValue);
119
            }catch (Exception e) {
120
                                return ValueFactory.createValue(0D);
121
                        }
122
            return ValueFactory.createValue(value);
123
        } else if (fieldType == 'C') {
124
            return ValueFactory.createValue(dbf.getStringFieldValue(
125
                    (int) rowIndex, fieldId).trim());
126
        } else if (fieldType == 'D') {
127
            String date = dbf.getStringFieldValue((int) rowIndex, fieldId).trim();
128
            // System.out.println(rowIndex + " data=" + date);
129
            if (date.length() == 0) {
130
                return null;
131
            }
132

    
133
            String year = date.substring(0, 4);
134
            String month = date.substring(4, 6);
135
            String day = date.substring(6, 8);
136
            DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, ukLocale);
137
            /* Calendar c = Calendar.getInstance();
138
            c.clear();
139
            c.set(Integer.parseInt(year), Integer.parseInt(month),
140
                Integer.parseInt(day));
141
            c.set(Calendar.MILLISECOND, 0); */
142
            String strAux = month + "/" + day + "/" + year;
143
            Date dat;
144
            try {
145
                dat = df.parse(strAux);
146
            } catch (ParseException e) {
147
                throw new DriverException("Bad Date Format");
148
            }
149

    
150
            // System.out.println("numReg = " + rowIndex + " date:" + dat.getTime());
151

    
152
            return ValueFactory.createValue(dat);
153
        } else {
154
            throw new DriverException("Unknown field type");
155
        }
156
    }
157

    
158
    /**
159
     * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldCount()
160
     */
161
    public int getFieldCount() throws DriverException {
162
        return dbf.getFieldCount();
163
    }
164

    
165
    /**
166
     * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldName(int)
167
     */
168
    public String getFieldName(int fieldId) throws DriverException {
169
        return dbf.getFieldName(fieldId);
170
    }
171

    
172
    /**
173
     * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getRowCount()
174
     */
175
    public long getRowCount() throws DriverException {
176
        return dbf.getRecordCount();
177
    }
178

    
179
    /**
180
     * @see com.hardcode.gdbms.engine.data.driver.FileDriver#fileAccepted(java.io.File)
181
     */
182
    public boolean fileAccepted(File f) {
183
        return f.getAbsolutePath().toUpperCase().endsWith("DBF");
184
    }
185

    
186
    /**
187
     * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#getFieldType(int)
188
     */
189
    public int getFieldType(int i) throws DriverException {
190
        char fieldType = fieldTypes[i];
191

    
192
        if (fieldType == 'L') {
193
            return Types.BOOLEAN;
194
        } else if ((fieldType == 'F') || (fieldType == 'N')) {
195
                if (dbf.getFieldDecimalLength(i)>0)
196
                        return Types.DOUBLE;
197
                else
198
                        return Types.INTEGER;
199
        } else if (fieldType == 'C') {
200
            return Types.VARCHAR;
201
        } else if (fieldType == 'D') {
202
            return Types.DATE;
203
        } else {
204
            throw new DriverException("Unknown field type");
205
        }
206
    }
207

    
208
    /**
209
     * @see com.hardcode.gdbms.engine.data.driver.DriverCommons#setDataSourceFactory(com.hardcode.gdbms.engine.data.DataSourceFactory)
210
     */
211
    public void setDataSourceFactory(DataSourceFactory dsf) {
212
        this.dsf = dsf;
213
    }
214

    
215
    private void writeToTemp(DataWare dataWare, File file) throws DriverException {
216
        DbaseFileWriterNIO dbfWrite = null;
217
        DbaseFileHeaderNIO myHeader;
218
        Value[] record;
219

    
220
        try {
221
            myHeader = DbaseFileHeaderNIO.createDbaseHeader(dataWare);
222

    
223
            myHeader.setNumRecords((int) dataWare.getRowCount());
224
            dbfWrite = new DbaseFileWriterNIO(myHeader,
225
                    (FileChannel) getWriteChannel(file.getPath()));
226
            record = new Value[dataWare.getFieldCount()];
227

    
228
            for (int j = 0; j < dataWare.getRowCount(); j++) {
229
                for (int r = 0; r < dataWare.getFieldCount(); r++) {
230
                    record[r] = dataWare.getFieldValue(j, r);
231
                }
232

    
233
                dbfWrite.write(record);
234
            }
235

    
236
            dbfWrite.close();
237
        } catch (IOException e) {
238
            throw new DriverException(e);
239
        }
240

    
241
    }
242

    
243
    /**
244
     * @see com.hardcode.gdbms.engine.data.driver.FileDriver#writeFile(com.hardcode.gdbms.engine.data.file.FileDataWare,
245
     *      java.io.File)
246
     */
247
    public void writeFile(FileDataWare dataWare)
248
        throws DriverException {
249

    
250
        String temp = dsf.getTempFile();
251

    
252
        writeToTemp(dataWare, new File(temp));
253

    
254
        try {
255
            FileChannel fcout = dbf.getWriteChannel();
256
            FileChannel fcin = new FileInputStream(temp).getChannel();
257

    
258
            DriverUtilities.copy(fcin, fcout);
259
        } catch (IOException e) {
260
            throw new DriverException(e);
261
        }
262
    }
263

    
264
    /**
265
     * DOCUMENT ME!
266
     *
267
     * @param path DOCUMENT ME!
268
     *
269
     * @return DOCUMENT ME!
270
     *
271
     * @throws IOException DOCUMENT ME!
272
     */
273
    private WritableByteChannel getWriteChannel(String path)
274
        throws IOException {
275
        WritableByteChannel channel;
276

    
277
        File f = new File(path);
278

    
279
        if (!f.exists()) {
280
            System.out.println("Creando fichero " + f.getAbsolutePath());
281

    
282
            if (!f.createNewFile()) {
283
                throw new IOException("Cannot create file " + f);
284
            }
285
        }
286

    
287
        RandomAccessFile raf = new RandomAccessFile(f, "rw");
288
        channel = raf.getChannel();
289

    
290
        return channel;
291
    }
292

    
293
    public void createSource(String arg0, String[] arg1, int[] arg2) throws IOException {
294
        DbaseFileHeaderNIO myHeader;
295

    
296
        int[] lengths = new int[arg2.length];
297
        for (int i = 0; i < arg2.length; i++) {
298
            lengths[i] = 100;
299
        }
300
        myHeader = DbaseFileHeaderNIO.createDbaseHeader(arg1, arg2, lengths);
301
        myHeader.setNumRecords(0);
302
        DbaseFileWriterNIO dbfWrite = new DbaseFileWriterNIO(myHeader,
303
                (FileChannel) getWriteChannel(arg0));
304
        dbfWrite = new DbaseFileWriterNIO(myHeader,
305
                (FileChannel) getWriteChannel(arg0));
306
    }
307

    
308
        public int getFieldWidth(int i) throws DriverException {
309
                return dbf.getFieldLength(i);
310
        }
311

    
312
        public IWriter getWriter() {
313
                return this;
314
        }
315

    
316
        public void preProcess() throws EditionException {
317
                dbfWriter.preProcess();
318

    
319
        }
320

    
321
        public void process(IRowEdited row) throws EditionException {
322
                dbfWriter.process(row);
323

    
324
        }
325

    
326
        public void postProcess() throws EditionException {
327
                dbfWriter.postProcess();
328
                try {
329
                        // Dbf
330
                        File dbfFile = fTemp;
331
                        FileChannel fcinDbf = new FileInputStream(dbfFile).getChannel();
332
                        FileChannel fcoutDbf = new FileOutputStream(file).getChannel();
333
                        DriverUtilities.copy(fcinDbf, fcoutDbf);
334

    
335
                        // Borramos los temporales
336
                        fTemp.delete();
337

    
338
                        // Reload
339
                        close();
340
                        open(file);
341

    
342

    
343

    
344
                } catch (FileNotFoundException e) {
345
                        throw new EditionException(e);
346
                } catch (IOException e) {
347
                        throw new EditionException(e);
348
                }
349

    
350

    
351
        }
352

    
353
        public String getCapability(String capability) {
354
                return dbfWriter.getCapability(capability);
355
        }
356

    
357
        public void setCapabilities(Properties capabilities) {
358
                dbfWriter.setCapabilities(capabilities);
359

    
360
        }
361

    
362
        public boolean canWriteAttribute(int sqlType) {
363
                return dbfWriter.canWriteAttribute(sqlType);
364
        }
365

    
366
        public void initialize(ITableDefinition tableDefinition) throws EditionException {
367
                int aux = (int)(Math.random() * 1000);
368
                fTemp = new File(tempDirectoryPath + "/tmpDbf" + aux + ".dbf");
369
                dbfWriter.setFile(fTemp);
370
                dbfWriter.initialize(tableDefinition);
371

    
372
        }
373

    
374
        public ITableDefinition getTableDefinition() {
375
                return dbfWriter.getTableDefinition();
376
        }
377

    
378
        public boolean canAlterTable() {
379
                return true;
380
        }
381

    
382
}