Statistics
| Revision:

root / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / edition / writers / dbf / DbfWriter.java @ 10627

History | View | Annotate | Download (7.33 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.hardcode.gdbms.driver.exceptions.InitializeWriterException;
12
import com.iver.cit.gvsig.exceptions.visitors.ProcessWriterVisitorException;
13
import com.iver.cit.gvsig.exceptions.visitors.StartWriterVisitorException;
14
import com.iver.cit.gvsig.exceptions.visitors.StopWriterVisitorException;
15
import com.iver.cit.gvsig.fmap.core.IRow;
16
import com.iver.cit.gvsig.fmap.drivers.FieldDescription;
17
import com.iver.cit.gvsig.fmap.drivers.ITableDefinition;
18
import com.iver.cit.gvsig.fmap.drivers.shp.DbaseFileHeaderNIO;
19
import com.iver.cit.gvsig.fmap.drivers.shp.DbaseFileWriterNIO;
20
import com.iver.cit.gvsig.fmap.edition.IRowEdited;
21
import com.iver.cit.gvsig.fmap.edition.fieldmanagers.AddFieldCommand;
22
import com.iver.cit.gvsig.fmap.edition.fieldmanagers.FieldCommand;
23
import com.iver.cit.gvsig.fmap.edition.fieldmanagers.RemoveFieldCommand;
24
import com.iver.cit.gvsig.fmap.edition.fieldmanagers.RenameFieldCommand;
25
import com.iver.cit.gvsig.fmap.edition.writers.AbstractWriter;
26
import com.iver.cit.gvsig.fmap.layers.FBitSet;
27

    
28
public class DbfWriter extends AbstractWriter {
29
        private String dbfPath = null;
30

    
31
        private DbaseFileWriterNIO dbfWrite;
32

    
33
        private DbaseFileHeaderNIO myHeader;
34

    
35
        private int numRows;
36

    
37
        private Object[] record;
38

    
39
        private ArrayList fieldCommands = new ArrayList();
40

    
41
        // private FLyrVect lyrVect;
42
        private FBitSet selection = null;
43

    
44
        private FieldDescription[] originalFields;
45

    
46
        public DbfWriter() {
47
                super();
48
                this.capabilities.setProperty("FieldNameMaxLength","10");
49
        }
50

    
51
        public void setFile(File f) {
52
                String strFichDbf = f.getAbsolutePath().replaceAll("\\.shp", ".dbf");
53
                dbfPath = strFichDbf.replaceAll("\\.SHP", ".DBF");
54
        }
55

    
56
        private WritableByteChannel getWriteChannel(String path) throws IOException {
57
                WritableByteChannel channel;
58

    
59
                File f = new File(path);
60

    
61
                if (!f.exists()) {
62
                        System.out.println("Creando fichero " + f.getAbsolutePath());
63

    
64
                        if (!f.createNewFile()) {
65
                                System.err.print("Error al crear el fichero "
66
                                                + f.getAbsolutePath());
67
                                throw new IOException("Cannot create file " + f);
68
                        }
69
                }
70

    
71
                RandomAccessFile raf = new RandomAccessFile(f, "rw");
72
                channel = raf.getChannel();
73

    
74
                return channel;
75
        }
76

    
77
        public void preProcess() throws StartWriterVisitorException {
78
                // Por ahora solo escribimos los primeros bytes
79
                // de las cabeceras. Luego en el postprocess los escribiremos
80
                // correctamente, con el fullExtent y el numero de
81
                // registros que tocan.
82
                alterTable();
83
                if (selection == null) {
84

    
85
                        try {
86
                                myHeader.setNumRecords(0);
87
                                dbfWrite = new DbaseFileWriterNIO(myHeader,
88
                                                (FileChannel) getWriteChannel(dbfPath));
89
                                record = new Object[myHeader.getNumFields()];
90
                                numRows = 0;
91

    
92
                        } catch (IOException e) {
93
                                throw new StartWriterVisitorException(getName(),e);
94
                        }
95
                }
96

    
97
        }
98

    
99
        public void process(IRowEdited row) throws ProcessWriterVisitorException {
100
                IRow rowEdit = row.getLinkedRow();
101
//                System.err.println("DBFWriter: " + row.getStatus() + " numRows = "
102
//                                + numRows);
103
                switch (row.getStatus()) {
104
                case IRowEdited.STATUS_ADDED:
105
                case IRowEdited.STATUS_ORIGINAL:
106
                case IRowEdited.STATUS_MODIFIED:
107
                        try {
108

    
109
                                for (int i = 0; i < record.length; i++)
110
                                        record[i] = rowEdit.getAttribute(i);
111
                                dbfWrite.write(record);
112
                                numRows++;
113

    
114
                        } catch (IOException e) {
115
                                throw new ProcessWriterVisitorException(getName(),e);
116
                        }
117

    
118
                }
119

    
120
        }
121

    
122
        public void postProcess() throws StopWriterVisitorException {
123
                try {
124
                        myHeader.setNumRecords(numRows);
125
                        dbfWrite = new DbaseFileWriterNIO(myHeader,
126
                                        (FileChannel) getWriteChannel(dbfPath));
127

    
128
                } catch (IOException e) {
129
                        throw new StopWriterVisitorException(getName(),e);
130
                }
131

    
132
        }
133

    
134
        public String getName() {
135
                return "DBF Writer";
136
        }
137

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

    
156
                }
157

    
158
                return false;
159
        }
160

    
161
        public void initialize(ITableDefinition tableDefinition)
162
                        throws InitializeWriterException {
163
                super.initialize(tableDefinition);
164
                originalFields = tableDefinition.getFieldsDesc();
165
                myHeader = DbaseFileHeaderNIO.createDbaseHeader(tableDefinition
166
                                .getFieldsDesc());
167
                if (dbfPath == null) {
168
                        throw new InitializeWriterException(getName(),null);
169
                }
170

    
171
        }
172

    
173
        public FieldDescription[] getOriginalFields() {
174
                return originalFields;
175
        }
176

    
177
        public boolean alterTable() throws StartWriterVisitorException {
178
                FieldDescription[] fieldsDesc =getFields();
179

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

    
198
        public void addField(FieldDescription fieldDesc) {
199
                AddFieldCommand c = new AddFieldCommand(fieldDesc);
200
                fieldCommands.add(c);
201
        }
202

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

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

    
223
        }
224

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

    
262
                        }
263

    
264
                }
265
                return (FieldDescription[]) aux.toArray(new FieldDescription[0]);
266
        }
267

    
268
        public boolean canAlterTable() {
269
                return true;
270
        }
271

    
272
        public boolean canSaveEdits() {
273
                File aux = new File(dbfPath);
274
                if (aux.canWrite()) return true;
275
                return false;
276
        }
277

    
278
}