Statistics
| Revision:

svn-gvsig-desktop / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / edition / writers / dbf / DbfWriter.java @ 6259

History | View | Annotate | Download (6.89 KB)

1
package com.iver.cit.gvsig.fmap.edition.writers.dbf;
2

    
3
import java.io.File;
4
import java.io.IOException;
5
import java.io.RandomAccessFile;
6
import java.nio.channels.FileChannel;
7
import java.nio.channels.WritableByteChannel;
8
import java.sql.Types;
9
import java.util.ArrayList;
10

    
11
import com.iver.cit.gvsig.fmap.core.IRow;
12
import com.iver.cit.gvsig.fmap.drivers.FieldDescription;
13
import com.iver.cit.gvsig.fmap.drivers.ITableDefinition;
14
import com.iver.cit.gvsig.fmap.drivers.shp.DbaseFileHeaderNIO;
15
import com.iver.cit.gvsig.fmap.drivers.shp.DbaseFileWriterNIO;
16
import com.iver.cit.gvsig.fmap.edition.EditionException;
17
import com.iver.cit.gvsig.fmap.edition.IFieldManager;
18
import com.iver.cit.gvsig.fmap.edition.IRowEdited;
19
import com.iver.cit.gvsig.fmap.edition.fieldmanagers.AddFieldCommand;
20
import com.iver.cit.gvsig.fmap.edition.fieldmanagers.FieldCommand;
21
import com.iver.cit.gvsig.fmap.edition.fieldmanagers.RemoveFieldCommand;
22
import com.iver.cit.gvsig.fmap.edition.fieldmanagers.RenameFieldCommand;
23
import com.iver.cit.gvsig.fmap.edition.writers.AbstractWriter;
24
import com.iver.cit.gvsig.fmap.layers.FBitSet;
25

    
26
public class DbfWriter extends AbstractWriter implements IFieldManager {
27
        private String dbfPath = null;
28

    
29
        private DbaseFileWriterNIO dbfWrite;
30

    
31
        private DbaseFileHeaderNIO myHeader;
32

    
33
        private int numRows;
34

    
35
        private Object[] record;
36

    
37
        private ArrayList fieldCommands = new ArrayList();
38

    
39
        // private FLyrVect lyrVect;
40
        private FBitSet selection = null;
41

    
42
        private FieldDescription[] originalFields;
43

    
44
        public void setFile(File f) {
45
                String strFichDbf = f.getAbsolutePath().replaceAll("\\.shp", ".dbf");
46
                dbfPath = strFichDbf.replaceAll("\\.SHP", ".DBF");
47
        }
48

    
49
        private WritableByteChannel getWriteChannel(String path) throws IOException {
50
                WritableByteChannel channel;
51

    
52
                File f = new File(path);
53

    
54
                if (!f.exists()) {
55
                        System.out.println("Creando fichero " + f.getAbsolutePath());
56

    
57
                        if (!f.createNewFile()) {
58
                                System.err.print("Error al crear el fichero "
59
                                                + f.getAbsolutePath());
60
                                throw new IOException("Cannot create file " + f);
61
                        }
62
                }
63

    
64
                RandomAccessFile raf = new RandomAccessFile(f, "rw");
65
                channel = raf.getChannel();
66

    
67
                return channel;
68
        }
69

    
70
        public void preProcess() throws EditionException {
71
                // Por ahora solo escribimos los primeros bytes
72
                // de las cabeceras. Luego en el postprocess los escribiremos
73
                // correctamente, con el fullExtent y el numero de
74
                // registros que tocan.
75
                alterTable();
76
                if (selection == null) {
77

    
78
                        try {
79
                                myHeader.setNumRecords(0);
80
                                dbfWrite = new DbaseFileWriterNIO(myHeader,
81
                                                (FileChannel) getWriteChannel(dbfPath));
82
                                record = new Object[myHeader.getNumFields()];
83
                                numRows = 0;
84

    
85
                        } catch (IOException e) {
86
                                e.printStackTrace();
87
                                throw new EditionException(e);
88
                        }
89
                }
90

    
91
        }
92

    
93
        public void process(IRowEdited row) throws EditionException {
94
                IRow rowEdit = (IRow) row.getLinkedRow();
95
                System.err.println("DBFWriter: " + row.getStatus() + " numRows = "
96
                                + numRows);
97
                switch (row.getStatus()) {
98
                case IRowEdited.STATUS_ADDED:
99
                case IRowEdited.STATUS_ORIGINAL:
100
                case IRowEdited.STATUS_MODIFIED:
101
                        try {
102

    
103
                                for (int i = 0; i < record.length; i++)
104
                                        record[i] = rowEdit.getAttribute(i);
105
                                dbfWrite.write(record);
106
                                numRows++;
107

    
108
                        } catch (IOException e) {
109
                                e.printStackTrace();
110
                                throw new EditionException(e);
111
                        }
112

    
113
                }
114

    
115
        }
116

    
117
        public void postProcess() throws EditionException {
118
                try {
119
                        myHeader.setNumRecords(numRows);
120
                        dbfWrite = new DbaseFileWriterNIO(myHeader,
121
                                        (FileChannel) getWriteChannel(dbfPath));
122

    
123
                } catch (IOException e) {
124
                        e.printStackTrace();
125
                        throw new EditionException(e);
126
                }
127

    
128
        }
129

    
130
        public String getName() {
131
                return "DBF Writer";
132
        }
133

    
134
        public boolean canWriteAttribute(int sqlType) {
135
                switch (sqlType) {
136
                case Types.DOUBLE:
137
                case Types.FLOAT:
138
                case Types.INTEGER:
139
                case Types.BIGINT:
140
                        return true;
141
                case Types.DATE:
142
                        return true;
143
                case Types.BIT:
144
                case Types.BOOLEAN:
145
                        return true;
146
                case Types.VARCHAR:
147
                case Types.CHAR:
148
                case Types.LONGVARCHAR:
149
                        return true; // TODO: Revisar esto, porque no creo que admita
150
                // campos muy grandes
151

    
152
                }
153

    
154
                return false;
155
        }
156

    
157
        public void initialize(ITableDefinition tableDefinition)
158
                        throws EditionException {
159
                super.initialize(tableDefinition);
160
                originalFields = tableDefinition.getFieldsDesc();
161
                myHeader = DbaseFileHeaderNIO.createDbaseHeader(tableDefinition
162
                                .getFieldsDesc());
163
                if (dbfPath == null) {
164
                        throw new EditionException(
165
                                        "DBFWriter: You need to use setFile before initialize.");
166
                }
167

    
168
        }
169

    
170
        public FieldDescription[] getOriginalFields() {
171
                return originalFields;
172
        }
173

    
174
        public boolean alterTable() throws EditionException {
175
                FieldDescription[] fieldsDesc =getFields();
176

    
177
                myHeader = DbaseFileHeaderNIO.createDbaseHeader(fieldsDesc);
178
                try {
179
                        dbfWrite = new DbaseFileWriterNIO(myHeader,
180
                                        (FileChannel) getWriteChannel(dbfPath));
181
//                        if (bNeedRewrite) {
182
//                                int aux = (int) (Math.random() * 1000);
183
//                                File fTemp = new File(System.getProperty("java.io.tmpdir")
184
//                                                + "/tmpDbf" + aux + ".dbf");
185
//
186
//                                // TODO: TERMINAR!!
187
//
188
//                        }
189
                } catch (IOException e) {
190
                        throw new EditionException(e);
191
                }
192
                return true;
193
        }
194

    
195
        public void addField(FieldDescription fieldDesc) {
196
                AddFieldCommand c = new AddFieldCommand(fieldDesc);
197
                fieldCommands.add(c);
198
        }
199

    
200
        public FieldDescription removeField(String fieldName) {
201
                RemoveFieldCommand c = new RemoveFieldCommand(fieldName);
202
                FieldDescription[] act = getFields();
203
                FieldDescription found = null;
204
                for (int i=0; i < act.length; i++)
205
                {
206
                        if (act[i].getFieldAlias().compareToIgnoreCase(fieldName) == 0)
207
                        {
208
                                found = act[i];
209
                                break;
210
                        }
211
                }
212
                fieldCommands.add(c);
213
                return found;
214
        }
215

    
216
        public void renameField(String antName, String newName) {
217
                RenameFieldCommand c = new RenameFieldCommand(antName, newName);
218
                fieldCommands.add(c);
219
                
220
        }
221

    
222
        public FieldDescription[] getFields() {
223
                ArrayList aux = new ArrayList();
224
                for (int i=0; i < getOriginalFields().length; i++)
225
                {
226
                        aux.add(getOriginalFields()[i]);
227
                }
228
                // procesamos comandos para devolver los campos reales.
229
                for (int j=0; j < fieldCommands.size(); j++)
230
                {
231
                        FieldCommand fc = (FieldCommand) fieldCommands.get(j);
232
                        if (fc instanceof AddFieldCommand)
233
                        {
234
                                AddFieldCommand ac = (AddFieldCommand) fc;
235
                                aux.add(ac.getFieldDesc());
236
                        }
237
                        if (fc instanceof RemoveFieldCommand)
238
                        {
239
                                RemoveFieldCommand rc = (RemoveFieldCommand) fc;
240
                                for (int k = 0; k < aux.size(); k++) {
241
                                        FieldDescription fAux = (FieldDescription) aux.get(k);
242
                                        if (fAux.getFieldAlias().compareTo(rc.getFieldName()) == 0) {
243
                                                aux.remove(k);
244
                                                break;
245
                                        }
246
                                }
247
                        }
248
                        if (fc instanceof RenameFieldCommand)
249
                        {
250
                                RenameFieldCommand renc = (RenameFieldCommand) fc;
251
                                for (int k = 0; k < aux.size(); k++) {
252
                                        FieldDescription fAux = (FieldDescription) aux.get(k);
253
                                        if (fAux.getFieldAlias().compareTo(renc.getAntName()) == 0) {
254
                                                fAux.setFieldAlias(renc.getNewName());
255
                                                break;
256
                                        }
257
                                }
258

    
259
                        }                        
260
                        
261
                }
262
                return (FieldDescription[]) aux.toArray(new FieldDescription[0]);
263
        }
264

    
265
}