Statistics
| Revision:

root / branches / simbologia / libraries / libFMap / src / com / iver / cit / gvsig / fmap / edition / writers / dbf / DbfWriter.java @ 10450

History | View | Annotate | Download (7.36 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
/**
27
 * @author   jaume dominguez faus - jaume.dominguez@iver.es
28
 */
29
public class DbfWriter extends AbstractWriter {
30
        private String dbfPath = null;
31

    
32
        private DbaseFileWriterNIO dbfWrite;
33

    
34
        private DbaseFileHeaderNIO myHeader;
35

    
36
        private int numRows;
37

    
38
        private Object[] record;
39

    
40
        private ArrayList fieldCommands = new ArrayList();
41

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

    
45
        /**
46
         * @uml.property  name="originalFields"
47
         * @uml.associationEnd  multiplicity="(0 -1)"
48
         */
49
        private FieldDescription[] originalFields;
50
        
51
        public DbfWriter() {
52
                super();
53
                this.capabilities.setProperty("FieldNameMaxLength","10");
54
        }
55

    
56
        public void setFile(File f) {
57
                String strFichDbf = f.getAbsolutePath().replaceAll("\\.shp", ".dbf");
58
                dbfPath = strFichDbf.replaceAll("\\.SHP", ".DBF");
59
        }
60

    
61
        private WritableByteChannel getWriteChannel(String path) throws IOException {
62
                WritableByteChannel channel;
63

    
64
                File f = new File(path);
65

    
66
                if (!f.exists()) {
67
                        System.out.println("Creando fichero " + f.getAbsolutePath());
68

    
69
                        if (!f.createNewFile()) {
70
                                System.err.print("Error al crear el fichero "
71
                                                + f.getAbsolutePath());
72
                                throw new IOException("Cannot create file " + f);
73
                        }
74
                }
75

    
76
                RandomAccessFile raf = new RandomAccessFile(f, "rw");
77
                channel = raf.getChannel();
78

    
79
                return channel;
80
        }
81

    
82
        public void preProcess() throws EditionException {
83
                // Por ahora solo escribimos los primeros bytes
84
                // de las cabeceras. Luego en el postprocess los escribiremos
85
                // correctamente, con el fullExtent y el numero de
86
                // registros que tocan.
87
                alterTable();
88
                if (selection == null) {
89

    
90
                        try {
91
                                myHeader.setNumRecords(0);
92
                                dbfWrite = new DbaseFileWriterNIO(myHeader,
93
                                                (FileChannel) getWriteChannel(dbfPath));
94
                                record = new Object[myHeader.getNumFields()];
95
                                numRows = 0;
96

    
97
                        } catch (IOException e) {
98
                                e.printStackTrace();
99
                                throw new EditionException(e);
100
                        }
101
                }
102

    
103
        }
104

    
105
        public void process(IRowEdited row) throws EditionException {
106
                IRow rowEdit = (IRow) row.getLinkedRow();
107
//                System.err.println("DBFWriter: " + row.getStatus() + " numRows = "
108
//                                + numRows);
109
                switch (row.getStatus()) {
110
                case IRowEdited.STATUS_ADDED:
111
                case IRowEdited.STATUS_ORIGINAL:
112
                case IRowEdited.STATUS_MODIFIED:
113
                        try {
114

    
115
                                for (int i = 0; i < record.length; i++)
116
                                        record[i] = rowEdit.getAttribute(i);
117
                                dbfWrite.write(record);
118
                                numRows++;
119

    
120
                        } catch (IOException e) {
121
                                e.printStackTrace();
122
                                throw new EditionException(e);
123
                        }
124

    
125
                }
126

    
127
        }
128

    
129
        public void postProcess() throws EditionException {
130
                try {
131
                        myHeader.setNumRecords(numRows);
132
                        dbfWrite = new DbaseFileWriterNIO(myHeader,
133
                                        (FileChannel) getWriteChannel(dbfPath));
134

    
135
                } catch (IOException e) {
136
                        e.printStackTrace();
137
                        throw new EditionException(e);
138
                }
139

    
140
        }
141

    
142
        public String getName() {
143
                return "DBF Writer";
144
        }
145

    
146
        public boolean canWriteAttribute(int sqlType) {
147
                switch (sqlType) {
148
                case Types.DOUBLE:
149
                case Types.FLOAT:
150
                case Types.INTEGER:
151
                case Types.BIGINT:
152
                        return true;
153
                case Types.DATE:
154
                        return true;
155
                case Types.BIT:
156
                case Types.BOOLEAN:
157
                        return true;
158
                case Types.VARCHAR:
159
                case Types.CHAR:
160
                case Types.LONGVARCHAR:
161
                        return true; // TODO: Revisar esto, porque no creo que admita
162
                // campos muy grandes
163

    
164
                }
165

    
166
                return false;
167
        }
168

    
169
        public void initialize(ITableDefinition tableDefinition)
170
                        throws EditionException {
171
                super.initialize(tableDefinition);
172
                originalFields = tableDefinition.getFieldsDesc();
173
                myHeader = DbaseFileHeaderNIO.createDbaseHeader(tableDefinition
174
                                .getFieldsDesc());
175
                if (dbfPath == null) {
176
                        throw new EditionException(
177
                                        "DBFWriter: You need to use setFile before initialize.");
178
                }
179

    
180
        }
181

    
182
        /**
183
         * @return
184
         * @uml.property  name="originalFields"
185
         */
186
        public FieldDescription[] getOriginalFields() {
187
                return originalFields;
188
        }
189

    
190
        public boolean alterTable() throws EditionException {
191
                FieldDescription[] fieldsDesc =getFields();
192

    
193
                myHeader = DbaseFileHeaderNIO.createDbaseHeader(fieldsDesc);
194
                try {
195
                        dbfWrite = new DbaseFileWriterNIO(myHeader,
196
                                        (FileChannel) getWriteChannel(dbfPath));
197
//                        if (bNeedRewrite) {
198
//                                int aux = (int) (Math.random() * 1000);
199
//                                File fTemp = new File(System.getProperty("java.io.tmpdir")
200
//                                                + "/tmpDbf" + aux + ".dbf");
201
//
202
//                                // TODO: TERMINAR!!
203
//
204
//                        }
205
                } catch (IOException e) {
206
                        throw new EditionException(e);
207
                }
208
                return true;
209
        }
210

    
211
        public void addField(FieldDescription fieldDesc) {
212
                AddFieldCommand c = new AddFieldCommand(fieldDesc);
213
                fieldCommands.add(c);
214
        }
215

    
216
        public FieldDescription removeField(String fieldName) {
217
                RemoveFieldCommand c = new RemoveFieldCommand(fieldName);
218
                FieldDescription[] act = getFields();
219
                FieldDescription found = null;
220
                for (int i=0; i < act.length; i++)
221
                {
222
                        if (act[i].getFieldAlias().compareToIgnoreCase(fieldName) == 0)
223
                        {
224
                                found = act[i];
225
                                break;
226
                        }
227
                }
228
                fieldCommands.add(c);
229
                return found;
230
        }
231

    
232
        public void renameField(String antName, String newName) {
233
                RenameFieldCommand c = new RenameFieldCommand(antName, newName);
234
                fieldCommands.add(c);
235
                
236
        }
237

    
238
        public FieldDescription[] getFields() {
239
                ArrayList aux = new ArrayList();
240
                for (int i=0; i < getOriginalFields().length; i++)
241
                {
242
                        aux.add(getOriginalFields()[i]);
243
                }
244
                // procesamos comandos para devolver los campos reales.
245
                for (int j=0; j < fieldCommands.size(); j++)
246
                {
247
                        FieldCommand fc = (FieldCommand) fieldCommands.get(j);
248
                        if (fc instanceof AddFieldCommand)
249
                        {
250
                                AddFieldCommand ac = (AddFieldCommand) fc;
251
                                aux.add(ac.getFieldDesc());
252
                        }
253
                        if (fc instanceof RemoveFieldCommand)
254
                        {
255
                                RemoveFieldCommand rc = (RemoveFieldCommand) fc;
256
                                for (int k = 0; k < aux.size(); k++) {
257
                                        FieldDescription fAux = (FieldDescription) aux.get(k);
258
                                        if (fAux.getFieldAlias().compareTo(rc.getFieldName()) == 0) {
259
                                                aux.remove(k);
260
                                                break;
261
                                        }
262
                                }
263
                        }
264
                        if (fc instanceof RenameFieldCommand)
265
                        {
266
                                RenameFieldCommand renc = (RenameFieldCommand) fc;
267
                                for (int k = 0; k < aux.size(); k++) {
268
                                        FieldDescription fAux = (FieldDescription) aux.get(k);
269
                                        if (fAux.getFieldAlias().compareTo(renc.getAntName()) == 0) {
270
                                                fAux.setFieldAlias(renc.getNewName());
271
                                                break;
272
                                        }
273
                                }
274

    
275
                        }                        
276
                        
277
                }
278
                return (FieldDescription[]) aux.toArray(new FieldDescription[0]);
279
        }
280

    
281
        public boolean canAlterTable() {
282
                return true;
283
        }
284

    
285
        public boolean canSaveEdits() {
286
                File aux = new File(dbfPath);                
287
                if (aux.canWrite()) return true;
288
                return false;
289
        }
290

    
291
}