Statistics
| Revision:

svn-gvsig-desktop / tags / v1_1_Build_1009 / libraries / libGDBMS / src / main / java / com / hardcode / gdbms / driver / dbf / DBFDriver.java @ 12649

History | View | Annotate | Download (8.87 KB)

1
package com.hardcode.gdbms.driver.dbf;
2

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

    
16
import com.hardcode.gdbms.driver.DriverUtilities;
17
import com.hardcode.gdbms.engine.data.DataSourceFactory;
18
import com.hardcode.gdbms.engine.data.driver.DriverException;
19
import com.hardcode.gdbms.engine.data.driver.FileDriver;
20
import com.hardcode.gdbms.engine.data.edition.DataWare;
21
import com.hardcode.gdbms.engine.data.file.FileDataWare;
22
import com.hardcode.gdbms.engine.values.Value;
23
import com.hardcode.gdbms.engine.values.ValueFactory;
24
import com.iver.cit.gvsig.fmap.drivers.dbf.DbaseFile;
25
import com.iver.cit.gvsig.fmap.drivers.shp.DbaseFileHeaderNIO;
26
import com.iver.cit.gvsig.fmap.drivers.shp.DbaseFileWriterNIO;
27

    
28

    
29
/**
30
 * DOCUMENT ME!
31
 *
32
 * @author Fernando Gonz?lez Cort?s
33
 */
34
public class DBFDriver implements FileDriver {
35
    //private File file;
36
    private static Locale ukLocale = new Locale("en", "UK"); // English, UK version
37
    private DbaseFile dbf = new DbaseFile();
38
    private char[] fieldTypes;
39
    private DataSourceFactory dsf;
40

    
41

    
42
    /**
43
     * @see com.hardcode.driverManager.Driver#getName()
44
     */
45
    public String getName() {
46
        return "gdbms dbf driver";
47
    }
48

    
49
    /**
50
     * @see com.hardcode.gdbms.engine.data.GDBMSDriver#open(java.io.File)
51
     */
52
    public void open(File file) throws IOException {
53
         dbf.open(file);
54

    
55
        try {
56
            fieldTypes = new char[getFieldCount()];
57

    
58
            for (int i = 0; i < fieldTypes.length; i++) {
59
                fieldTypes[i] = dbf.getFieldType(i);
60
            }
61
        } catch (DriverException e) {
62
            throw new IOException(e.getMessage());
63
        }
64
    }
65

    
66
    /**
67
     * @see com.hardcode.gdbms.engine.data.GDBMSDriver#close()
68
     */
69
    public void close() throws IOException {
70
        dbf.close();
71
    }
72

    
73
    /**
74
     * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldValue(long,
75
     *      int)
76
     */
77
    public Value getFieldValue(long rowIndex, int fieldId)
78
    throws DriverException {
79
            // Field Type (C  or M)
80
            char cfieldType = fieldTypes[fieldId];
81
            int fieldType = getFieldType(fieldId);
82

    
83
            String strValue;
84

    
85
            if (cfieldType == 'D') {
86
                    String date;
87
                    try {
88
                            date = dbf.getStringFieldValue((int) rowIndex, fieldId).trim();
89
                    } catch (UnsupportedEncodingException e1) {
90
                            throw new DriverException(e1);
91
                    }
92
                    // System.out.println(rowIndex + " data=" + date);
93
                    if (date.length() == 0) {
94
                            return null;
95
                    }
96

    
97
                    String year = date.substring(0, 4);
98
                    String month = date.substring(4, 6);
99
                    String day = date.substring(6, 8);
100
                    DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, ukLocale);
101
                    /* Calendar c = Calendar.getInstance();
102
        c.clear();
103
        c.set(Integer.parseInt(year), Integer.parseInt(month),
104
            Integer.parseInt(day));
105
        c.set(Calendar.MILLISECOND, 0); */
106
                    String strAux = month + "/" + day + "/" + year;
107
                    Date dat;
108
                    try {
109
                            dat = df.parse(strAux);
110
                    } catch (ParseException e) {
111
                            throw new DriverException("Bad Date Format");
112
                    }
113

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

    
116
                    return ValueFactory.createValue(dat);
117
            } else {
118
                    try {
119
                            strValue = dbf.getStringFieldValue((int) rowIndex, fieldId);
120
                    } catch (UnsupportedEncodingException e1) {
121
                            e1.printStackTrace();
122
                            throw new DriverException(e1);
123
                    }
124
                    strValue = strValue.trim();
125
                           if (fieldType == Types.BOOLEAN){
126
                                   strValue = strValue.toLowerCase();
127
                                 strValue = Boolean.toString(strValue.equals("t") || strValue.equals("y"));
128
                           }
129

    
130
                    try {
131
                            return ValueFactory.createValueByType(strValue, fieldType);
132
                    } catch (Exception e) {
133
                            if (fieldType == Types.INTEGER){
134
                                    // Habria que quejarse???
135
                                    return ValueFactory.createValue(0);
136
                            } else{
137
                                        // OJO: Habria que revisar el resto de tipos
138
                                        // De momento lanzamos la excepcion
139
                                    throw new DriverException("Bad Field Value: '" + strValue+"' (rowIndes: "+rowIndex + " fielId: "+ fieldId +" fieldType: " + fieldType + ")");
140
                            }
141
                    }
142
            }
143
    }
144

    
145
    /**
146
     * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldCount()
147
     */
148
    public int getFieldCount() throws DriverException {
149
        return dbf.getFieldCount();
150
    }
151

    
152
    /**
153
     * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldName(int)
154
     */
155
    public String getFieldName(int fieldId) throws DriverException {
156
        return dbf.getFieldName(fieldId);
157
    }
158

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

    
166
    /**
167
     * @see com.hardcode.gdbms.engine.data.driver.FileDriver#fileAccepted(java.io.File)
168
     */
169
    public boolean fileAccepted(File f) {
170
        return f.getAbsolutePath().toUpperCase().endsWith("DBF");
171
    }
172

    
173
    /**
174
     * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#getFieldType(int)
175
     */
176
    public int getFieldType(int i) throws DriverException {
177
        char fieldType = fieldTypes[i];
178

    
179
        if (fieldType == 'L') {
180
            return Types.BOOLEAN;
181
        } else if ((fieldType == 'F') || (fieldType == 'N')) {
182
            return Types.DOUBLE;
183
        } else if (fieldType == 'C') {
184
            return Types.VARCHAR;
185
        } else if (fieldType == 'D') {
186
            return Types.DATE;
187
        } else {
188
            throw new DriverException("Unknown field type");
189
        }
190
    }
191

    
192
    /**
193
     * @see com.hardcode.gdbms.engine.data.driver.DriverCommons#setDataSourceFactory(com.hardcode.gdbms.engine.data.DataSourceFactory)
194
     */
195
    public void setDataSourceFactory(DataSourceFactory dsf) {
196
        this.dsf = dsf;
197
    }
198

    
199
    private void writeToTemp(DataWare dataWare, File file) throws DriverException {
200
        DbaseFileWriterNIO dbfWrite = null;
201
        DbaseFileHeaderNIO myHeader;
202
        Value[] record;
203

    
204
        try {
205
            myHeader = DbaseFileHeaderNIO.createDbaseHeader(dataWare);
206

    
207
            myHeader.setNumRecords((int) dataWare.getRowCount());
208
            dbfWrite = new DbaseFileWriterNIO(myHeader,
209
                    (FileChannel) getWriteChannel(file.getPath()));
210
            record = new Value[dataWare.getFieldCount()];
211

    
212
            for (int j = 0; j < dataWare.getRowCount(); j++) {
213
                for (int r = 0; r < dataWare.getFieldCount(); r++) {
214
                    record[r] = dataWare.getFieldValue(j, r);
215
                }
216

    
217
                dbfWrite.write(record);
218
            }
219

    
220
            dbfWrite.close();
221
        } catch (IOException e) {
222
            throw new DriverException(e);
223
        }
224

    
225
    }
226

    
227
    /**
228
     * @see com.hardcode.gdbms.engine.data.driver.FileDriver#writeFile(com.hardcode.gdbms.engine.data.file.FileDataWare,
229
     *      java.io.File)
230
     */
231
    public void writeFile(FileDataWare dataWare)
232
        throws DriverException {
233

    
234
        String temp = dsf.getTempFile();
235

    
236
        writeToTemp(dataWare, new File(temp));
237

    
238
        try {
239
            FileChannel fcout = dbf.getWriteChannel();
240
            FileChannel fcin = new FileInputStream(temp).getChannel();
241

    
242
            DriverUtilities.copy(fcin, fcout);
243
        } catch (IOException e) {
244
            throw new DriverException(e);
245
        }
246
    }
247

    
248
    /**
249
     * DOCUMENT ME!
250
     *
251
     * @param path DOCUMENT ME!
252
     *
253
     * @return DOCUMENT ME!
254
     *
255
     * @throws IOException DOCUMENT ME!
256
     */
257
    private WritableByteChannel getWriteChannel(String path)
258
        throws IOException {
259
        WritableByteChannel channel;
260

    
261
        File f = new File(path);
262

    
263
        if (!f.exists()) {
264
            System.out.println("Creando fichero " + f.getAbsolutePath());
265

    
266
            if (!f.createNewFile()) {
267
                throw new IOException("Cannot create file " + f);
268
            }
269
        }
270

    
271
        RandomAccessFile raf = new RandomAccessFile(f, "rw");
272
        channel = raf.getChannel();
273

    
274
        return channel;
275
    }
276

    
277
    public void createSource(String arg0, String[] arg1, int[] arg2) throws IOException {
278
        DbaseFileHeaderNIO myHeader;
279

    
280
        int[] lengths = new int[arg2.length];
281
        for (int i = 0; i < arg2.length; i++) {
282
            lengths[i] = 100;
283
        }
284
        myHeader = DbaseFileHeaderNIO.createDbaseHeader(arg1, arg2, lengths);
285
        myHeader.setNumRecords(0);
286
        DbaseFileWriterNIO dbfWrite = new DbaseFileWriterNIO(myHeader,
287
                (FileChannel) getWriteChannel(arg0));
288
        dbfWrite = new DbaseFileWriterNIO(myHeader,
289
                (FileChannel) getWriteChannel(arg0));
290
    }
291

    
292
        public int getFieldWidth(int i) throws DriverException {
293
                return dbf.getFieldLength(i);
294
        }
295
}