Statistics
| Revision:

root / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / edition / EditableAdapter.java @ 6323

History | View | Annotate | Download (37.3 KB)

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

    
3
import java.io.IOException;
4
import java.util.ArrayList;
5
import java.util.Collection;
6
import java.util.HashMap;
7
import java.util.Iterator;
8
import java.util.TreeMap;
9

    
10
import com.hardcode.driverManager.Driver;
11
import com.hardcode.driverManager.DriverLoadException;
12
import com.hardcode.gdbms.engine.data.DataSourceFactory;
13
import com.hardcode.gdbms.engine.data.NoSuchTableException;
14
import com.hardcode.gdbms.engine.data.driver.DriverException;
15
import com.hardcode.gdbms.engine.data.driver.ObjectDriver;
16
import com.hardcode.gdbms.engine.data.edition.DataWare;
17
import com.hardcode.gdbms.engine.values.Value;
18
import com.iver.cit.gvsig.fmap.core.DefaultRow;
19
import com.iver.cit.gvsig.fmap.core.IRow;
20
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
21
import com.iver.cit.gvsig.fmap.drivers.FieldDescription;
22
import com.iver.cit.gvsig.fmap.drivers.ITableDefinition;
23
import com.iver.cit.gvsig.fmap.drivers.TableDefinition;
24
import com.iver.cit.gvsig.fmap.edition.commands.AddFieldCommand;
25
import com.iver.cit.gvsig.fmap.edition.commands.AddRowCommand;
26
import com.iver.cit.gvsig.fmap.edition.commands.Command;
27
import com.iver.cit.gvsig.fmap.edition.commands.CommandCollection;
28
import com.iver.cit.gvsig.fmap.edition.commands.CommandRecord;
29
import com.iver.cit.gvsig.fmap.edition.commands.MemoryCommandRecord;
30
import com.iver.cit.gvsig.fmap.edition.commands.ModifyRowCommand;
31
import com.iver.cit.gvsig.fmap.edition.commands.RemoveFieldCommand;
32
import com.iver.cit.gvsig.fmap.edition.commands.RemoveRowCommand;
33
import com.iver.cit.gvsig.fmap.edition.commands.RenameFieldCommand;
34
import com.iver.cit.gvsig.fmap.edition.fieldmanagers.AbstractFieldManager;
35
import com.iver.cit.gvsig.fmap.edition.rules.IRule;
36
import com.iver.cit.gvsig.fmap.layers.FBitSet;
37
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
38
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
39
import com.iver.cit.gvsig.fmap.operations.Cancel;
40

    
41
/**
42
 * DOCUMENT ME!
43
 * 
44
 * @author Vicente Caballero Navarro
45
 */
46
public class EditableAdapter implements IEditableSource, IWriteable {
47
        protected boolean isEditing = false;
48

    
49
        private SelectableDataSource ds = null;
50

    
51
        protected FBitSet delRows = new FBitSet();
52

    
53
        private CommandRecord cr;
54

    
55
        protected IWriter writer;
56

    
57
        /**
58
         * Flag que indica que hay que tomar las siguientes operaciones como una
59
         * operaci?n at?mica
60
         */
61
        private boolean complex = false;
62

    
63
        private CommandCollection commands = null;
64

    
65
        protected ArrayList listFields = new ArrayList();
66

    
67
        protected ArrayList listInternalFields = new ArrayList();
68

    
69
        /**
70
         * La clave ser? el fieldIndex. Para buscar si un value de una row ha de ser
71
         * rellenado con defaultValue o con lo que venga del expansion file,
72
         * miraremos si existe en este hash. Si existe, usamos el value del
73
         * expansion file. Si no existe, usamos el defaultValue del campo busc?ndolo
74
         * en la lista internalFields. Por cierto, en listInternalFields NO se
75
         * borran campos. Solo se marcan como borrados.
76
         */
77
        protected TreeMap actualFields; // la clave ser? el fieldIndex.
78

    
79
        protected class MyFieldManager extends AbstractFieldManager {
80

    
81
                public boolean alterTable() throws EditionException {
82
                        return getFieldManager().alterTable();
83
                }
84

    
85
                public void addField(FieldDescription fieldDesc) {
86
                        super.addField(fieldDesc);
87
                }
88

    
89
                public FieldDescription removeField(String fieldName) {
90
                        // TODO Auto-generated method stub
91
                        return super.removeField(fieldName);
92
                }
93

    
94
                public void renameField(String antName, String newName) {
95
                        // TODO Auto-generated method stub
96
                        super.renameField(antName, newName);
97
                }
98

    
99
        }
100

    
101
        /*
102
         * Establece una relaci?n entre los ?ndices de las geometr?as en el
103
         * EditableFeatureSource y los ?ndices en el fichero de expansi?n FJP:
104
         * CAMBIO: NECESITAMOS TRABAJAR CON FEATURE Y FEATUREITERATOR PARA IR
105
         * PREPARANDO EL CAMINO, GUARDAMOS EL FEATUREID (STRING) COMO CLAVE, Y COMO
106
         * VALOR, EL INDICE DENTRO DEL FICHERO DE EXPANSION (Integer). Lo de que
107
         * FeatureId sea un String es por compatibilidad con OGC. Seg?n OGC, una
108
         * Feature tiene que tener un Id string En el caso de los randomaccess,
109
         * ser?n el id de registro En los casos de base de datos espaciales, supongo
110
         * que siempre ser? num?rico tambi?n, pero lo tendremos que convertir a
111
         * string. Lo que est? claro es que NO se puede confiar nunca en que sea
112
         * algo correlativo (1, 2, 3, 4, 5, ... => FALSO!!)
113
         */
114
        protected HashMap relations = new HashMap();
115

    
116
        /*
117
         * Fichero en el que se guardan las nuevas geometr?as, producto de adiciones
118
         * o de modificaciones
119
         */
120
        protected ExpansionFile expansionFile;
121

    
122
        protected int numAdd = 0;
123

    
124
        private ObjectDriver editingDriver = new myObjectDriver();
125

    
126
        private SelectableDataSource ods;
127

    
128
        private ArrayList editionListeners = new ArrayList();
129

    
130
        private ArrayList rules = new ArrayList();
131

    
132
        protected int actualIndexFields;
133

    
134
        /**
135
         * Crea un nuevo EditableAdapter.
136
         */
137
        public EditableAdapter() {
138
                expansionFile = new MemoryExpansionFile(this);
139
                cr = new MemoryCommandRecord();
140
        }
141

    
142
        /**
143
         * DOCUMENT ME!
144
         * 
145
         * @param ds
146
         *            DOCUMENT ME!
147
         * @throws DriverException 
148
         */
149
        public void setOriginalDataSource(SelectableDataSource ds) throws DriverException {
150
                this.ods = ds;
151
                initalizeFields(ds);
152
                
153
        }
154

    
155
        /**
156
         * @param ds
157
         * @throws DriverException
158
         */
159
        private void initalizeFields(SelectableDataSource ds) throws DriverException {
160
                FieldDescription[] fields = ds.getFieldsDescription();
161
                listInternalFields.clear();
162
                actualFields = new TreeMap();
163
                for (int i=0; i < fields.length; i++)
164
                {
165
                        InternalField field = new InternalField(fields[i], InternalField.ORIGINAL, new Integer(i));
166
                        listFields.add(field);
167
                        field.setFieldIndex(i);
168
                        actualFields.put(field.getFieldId(), field);
169
                }
170
                try {
171
                        fieldsChanged();
172
                } catch (EditionException e) {
173
                        e.printStackTrace();
174
                        throw new DriverException(e);
175
                }
176
        }
177

    
178
        private void fieldsChanged() throws EditionException {
179
                listInternalFields.add(actualFields.clone());
180
                actualIndexFields = listInternalFields.size()-1;
181
                try {
182
                        getRecordset().mapExternalFields();
183
                } catch (DriverLoadException e) {
184
                        e.printStackTrace();
185
                        throw new EditionException(e);
186
                } catch (DriverException e) {
187
                        e.printStackTrace();
188
                        throw new EditionException(e);
189
                }
190
        }
191

    
192
        /**
193
         * DOCUMENT ME!
194
         * 
195
         * @throws EditionException
196
         *             DOCUMENT ME!
197
         */
198
        public void startEdition(int sourceType) throws EditionException {
199
                isEditing = true;
200
                // Obtenemos el driver y vemos si implementa IWriter.
201
                /*
202
                 * DataWare dataWare =
203
                 * ods.getDataWare(DataSourceFactory.DATA_WARE_DIRECT_MODE);
204
                 * dataWare.get
205
                 */
206
                Driver drv = ods.getDriver();
207
                if (drv instanceof IWriteable) {
208
                        setWriter(((IWriteable) drv).getWriter());
209
                }
210

    
211
                fireStartEditionEvent(sourceType);
212
        }
213

    
214
        /**
215
         * Se ejecuta preProcess() del IWriter, luego se itera por los registros
216
         * borrados por si el IWriter los quiere borrar (solo ser? necesario cuando
217
         * escribimos sobre la misma tabla) y luego se itera por los nuevos
218
         * registros llamando a process con el registro correcto. (A?adidos,
219
         * modificados). Para finalizar, se ejecuta PostProcess
220
         * 
221
         * @param writer
222
         *            IWriter que recibir? las llamadas.
223
         * 
224
         * @throws EditionException
225
         *             DOCUMENT ME!
226
         */
227
        public void stopEdition(IWriter writer, int sourceType)
228
                        throws EditionException {
229

    
230
                saveEdits(writer, sourceType);
231
                isEditing = false;
232
                fireStopEditionEvent(sourceType);
233
        }
234

    
235
        public void saveEdits(IWriter writer, int sourceType)
236
                        throws EditionException {
237
                writer.preProcess();
238

    
239
                try {
240

    
241
                        // Procesamos primero los borrados.
242
                        // Cuando se genere un tema nuevo, no se les debe hacer caso
243
                        // a estos registros
244

    
245
                        for (int i = delRows.nextSetBit(0); i >= 0; i = delRows
246
                                        .nextSetBit(i + 1)) {
247
                                int calculatedIndex = i;
248
                                Integer integer = new Integer(calculatedIndex);
249
                                // Si no est? en el fichero de expansi?n, es de los originales
250
                                // y hay que borrarlo
251
                                DefaultRowEdited edRow = null;
252
                                if (!relations.containsKey(integer)) {
253
                                        edRow = new DefaultRowEdited(new DefaultRow(ods
254
                                                        .getRow(calculatedIndex)),
255
                                                        DefaultRowEdited.STATUS_DELETED, calculatedIndex);
256
                                        writer.process(edRow);
257
                                } else {
258
                                        int num = ((Integer) relations.get(integer)).intValue();
259

    
260
                                        // return expansionFile.getRow(num);
261
                                        IRowEdited rowFromExpansion = expansionFile.getRow(num);
262
                                        // ?Habr?a que hacer aqu? setID(index + "")?
263
                                        edRow = new DefaultRowEdited(rowFromExpansion
264
                                                        .getLinkedRow().cloneRow(),
265
                                                        DefaultRowEdited.STATUS_DELETED, calculatedIndex);
266
                                        writer.process(edRow);
267
                                }
268

    
269
                        }
270

    
271
                        int rowCount = getRowCount();
272
                        for (int i = 0; i < rowCount; i++) {
273
                                IRowEdited rowEdited = getRow(i);
274

    
275
                                if (rowEdited != null) {
276
                                        writer.process(rowEdited);
277
                                }
278
                        }
279
                        writer.postProcess();
280

    
281
                        ods.reload();
282
                        initalizeFields(ods);
283
                        
284
                } catch (DriverIOException e) {
285
                        e.printStackTrace();
286
                        throw new EditionException(e);
287
                } catch (IOException e) {
288
                        e.printStackTrace();
289
                        throw new EditionException(e);
290
                } catch (DriverException e) {
291
                        e.printStackTrace();
292
                        throw new EditionException(e);
293
                }
294

    
295
        }
296

    
297
        /**
298
         * DOCUMENT ME!
299
         * 
300
         * @throws IOException
301
         *             DOCUMENT ME!
302
         */
303
        public void cancelEdition(int sourceType) throws IOException {
304
                isEditing = false;
305
                try {
306
                        clean();
307
                } catch (DriverException e) {
308
                        e.printStackTrace();
309
                        throw new IOException("Error: " + e.getMessage());
310
                }
311
                fireCancelEditionEvent(sourceType);
312
        }
313

    
314
        /*
315
         * (non-Javadoc)
316
         * 
317
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#getRow(int)
318
         */
319
        public IRowEdited getRow(int index) throws DriverIOException, IOException {
320
                int calculatedIndex = getCalculatedIndex(index);
321
                Integer integer = new Integer(calculatedIndex);
322
                DefaultRowEdited edRow = null;
323
                // Si no est? en el fichero de expansi?n
324
                if (!relations.containsKey(integer)) {
325
                        try {
326
                                /*
327
                                 * edRow = new DefaultRowEdited(new
328
                                 * DefaultRow(ods.getRow(calculatedIndex), "" + index),
329
                                 * DefaultRowEdited.STATUS_ORIGINAL, index);
330
                                 */
331
                                DefaultRow auxR = new DefaultRow(ods.getRow(calculatedIndex));
332
                                edRow = new DefaultRowEdited(auxR,
333
                                                DefaultRowEdited.STATUS_ORIGINAL, index);
334
                                return createExternalRow(edRow, 0);
335
//                                edRow = new DefaultRowEdited(new DefaultRow(ods
336
//                                                .getRow(calculatedIndex)),
337
//                                                DefaultRowEdited.STATUS_ORIGINAL, index);
338
                        } catch (DriverException e) {
339
                                throw new DriverIOException(e);
340
                        }
341
                } else {
342
                        int num = ((Integer) relations.get(integer)).intValue();
343

    
344
                        // return expansionFile.getRow(num);
345
                        // ExpansionFile ya entrega el registro formateado como debe
346
                        IRowEdited rowFromExpansion = expansionFile.getRow(num);
347
                        // ?Habr?a que hacer aqu? setID(index + "")?
348
                        edRow = new DefaultRowEdited(rowFromExpansion.getLinkedRow()
349
                                        .cloneRow(), rowFromExpansion.getStatus(), index);
350
                        return edRow;
351
                }
352
                
353
                
354

    
355
        }
356

    
357
        /**
358
         * DOCUMENT ME!
359
         * 
360
         * @return DOCUMENT ME!
361
         * 
362
         * @throws DriverIOException
363
         *             DOCUMENT ME!
364
         * @throws IOException
365
         *             DOCUMENT ME!
366
         */
367
        public int getRowCount() throws DriverIOException, IOException {
368
                try {
369
                        return (int) (ods.getRowCount() + numAdd) - delRows.cardinality();// -
370
                        // expansionFile.getInvalidRows().cardinality();
371
                } catch (DriverException e) {
372
                        throw new DriverIOException(e);
373
                }
374

    
375
        }
376

    
377
        /*
378
         * (non-Javadoc)
379
         * 
380
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#addRow(com.iver.cit.gvsig.fmap.core.IRow,
381
         *      java.lang.String)
382
         */
383
        public int addRow(IRow row, String descrip, int sourceType)
384
                        throws DriverIOException, IOException {
385

    
386
                try {
387
                        validateRow(row);
388
                } catch (EditionException e) {
389
                        e.printStackTrace();
390
                        throw new IOException(e.getMessage());
391
                }
392

    
393
                int calculatedIndex = doAddRow(row, sourceType);
394
                Command command = new AddRowCommand(this, row, calculatedIndex,
395
                                sourceType);
396
                command.setDescription(descrip);
397
                if (complex) {
398
                        commands.add(command);
399
                } else {
400
                        cr.pushCommand(command);
401
                }
402

    
403
                return calculatedIndex;
404
        }
405

    
406
        /**
407
         * DOCUMENT ME!
408
         * 
409
         * @throws DriverIOException
410
         *             DOCUMENT ME!
411
         * @throws IOException
412
         *             DOCUMENT ME!
413
         */
414
        public void undo() throws DriverIOException, IOException {
415
                // seleccion.clear();
416
                if (cr.moreUndoCommands()) {
417
                        cr.undoCommand();
418
                }
419
        }
420

    
421
        /**
422
         * DOCUMENT ME!
423
         * 
424
         * @throws DriverIOException
425
         *             DOCUMENT ME!
426
         * @throws IOException
427
         *             DOCUMENT ME!
428
         */
429
        public void redo() throws DriverIOException, IOException {
430
                // seleccion.clear();
431
                if (cr.moreRedoCommands()) {
432
                        cr.redoCommand();
433
                }
434
        }
435

    
436
        /*
437
         * (non-Javadoc)
438
         * 
439
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#removeRow(int)
440
         */
441
        public void removeRow(int index, String descrip, int sourceType)
442
                        throws IOException, DriverIOException {
443

    
444
                int calculatedIndex = getCalculatedIndex(index);
445
                Command command = new RemoveRowCommand(this, calculatedIndex,
446
                                sourceType);
447
                command.setDescription(descrip);
448
                if (complex) {
449
                        commands.add(command);
450
                } else {
451
                        cr.pushCommand(command);
452
                }
453
                doRemoveRow(calculatedIndex, sourceType);
454

    
455
        }
456

    
457
        /*
458
         * (non-Javadoc)
459
         * 
460
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#modifyRow(int,
461
         *      com.iver.cit.gvsig.fmap.core.IRow)
462
         */
463
        public int modifyRow(int index, IRow row, String descrip, int sourceType)
464
                        throws IOException, DriverIOException {
465

    
466
                try {
467
                        validateRow(row);
468
                } catch (EditionException e) {
469
                        e.printStackTrace();
470
                        throw new IOException(e.getMessage());
471
                }
472

    
473
                int calculatedIndex = getCalculatedIndex(index);
474
                int pos = doModifyRow(calculatedIndex, row, sourceType);
475
                Command command = new ModifyRowCommand(this, calculatedIndex, pos, row,
476
                                sourceType);
477
                command.setDescription(descrip);
478
                if (complex) {
479
                        commands.add(command);
480
                } else {
481
                        cr.pushCommand(command);
482
                }
483

    
484
                return pos;
485
        }
486

    
487
        /**
488
         * DOCUMENT ME!
489
         */
490
        public void compact() {
491
                expansionFile.compact(relations);
492
        }
493

    
494
        /**
495
         * DOCUMENT ME!
496
         */
497
        public void startComplexRow() {
498
                complex = true;
499
                commands = new CommandCollection();
500
        }
501

    
502
        /**
503
         * DOCUMENT ME!
504
         * 
505
         * @throws IOException
506
         *             DOCUMENT ME!
507
         * @throws DriverIOException
508
         *             DOCUMENT ME!
509
         */
510
        public void endComplexRow(String description) throws IOException,
511
                        DriverIOException {
512
                commands.setDescription(description);
513
                cr.pushCommand(commands);
514
                complex = false;
515
        }
516

    
517
        /**
518
         * Actualiza en el mapa de ?ndices, la posici?n en la que estaba la
519
         * geometr?a antes de ser modificada. Se marca como v?lida, en caso de que
520
         * fuera una modificaci?n de una geometr?a que estuviese en el fichero de
521
         * expansi?n antes de ser modificada y se pone el puntero de escritura del
522
         * expansion file a justo despues de la penultima geometr?a
523
         * 
524
         * @param geometryIndex
525
         *            ?ndice de la geometr?a que se quiere deshacer su modificaci?n
526
         * @param previousExpansionFileIndex
527
         *            ?ndice que ten?a antes la geometr?a en el expansionFile. Si
528
         *            vale -1 quiere decir que es una modificaci?n de una geometr?a
529
         *            original y por tanto no hay que actualizar el mapa de indices
530
         *            sino eliminar su entrada.
531
         * 
532
         * @throws IOException
533
         * @throws DriverIOException
534
         */
535
        public void undoModifyRow(int geometryIndex,
536
                        int previousExpansionFileIndex, int sourceType) throws IOException,
537
                        DriverIOException {
538

    
539
                if (previousExpansionFileIndex == -1) {
540
                        DefaultRowEdited edRow = null;
541
                        try {
542
                                edRow = new DefaultRowEdited(new DefaultRow(ods
543
                                                .getRow(geometryIndex)),
544
                                                DefaultRowEdited.STATUS_ORIGINAL, geometryIndex);
545
                        } catch (DriverException e) {
546
                                e.printStackTrace();
547
                        }
548
                        boolean cancel = fireBeforeModifyRow(edRow, geometryIndex,
549
                                        sourceType);
550
                        if (cancel)
551
                                return;
552
                        // Se elimina de las relaciones y del fichero de expansi?n
553
                        relations.remove(new Integer(geometryIndex));
554
                        expansionFile.deleteLastRow();
555
                } else {
556
                        boolean cancel = fireBeforeModifyRow(expansionFile
557
                                        .getRow(previousExpansionFileIndex), geometryIndex,
558
                                        sourceType);
559
                        if (cancel)
560
                                return;
561
                        // Se actualiza la relaci?n de ?ndices
562
                        relations.put(new Integer(geometryIndex), new Integer(
563
                                        previousExpansionFileIndex));
564
                }
565
                fireAfterModifyRow(geometryIndex, sourceType);
566
        }
567

    
568
        /**
569
         * Elimina una geometria. Si es una geometr?a original de la capa en edici?n
570
         * se marca como eliminada (haya sido modificada o no). Si es una geometr?a
571
         * a?adida posteriormente se invalida en el fichero de expansi?n, para que
572
         * una futura compactaci?n termine con ella.
573
         * 
574
         * @param index
575
         *            ?ndice de la geometr?a.
576
         * 
577
         * @throws DriverIOException
578
         * @throws IOException
579
         */
580
        public IRow doRemoveRow(int index, int sourceType)
581
                        throws DriverIOException, IOException {
582
                boolean cancel = fireBeforeRemoveRow(index, sourceType);
583
                if (cancel)
584
                        return null;
585
                // Llega un calculatedIndex
586
                delRows.set(index, true);
587
                System.err.println("Elimina una Row en la posici?n: " + index);
588
                // TODO: Con tablas no es necesario devolver la anterior feature. Por
589
                // ahora.
590
                fireAfterRemoveRow(index, sourceType);
591
                return null;
592
        }
593

    
594
        /**
595
         * Si se intenta modificar una geometr?a original de la capa en edici?n se
596
         * a?ade al fichero de expansi?n y se registra la posici?n en la que se
597
         * a?adi?. Si se intenta modificar una geometria que se encuentra en el
598
         * fichero de expansi?n (por ser nueva o original pero modificada) se invoca
599
         * el m?todo modifyGeometry y se actualiza el ?ndice de la geometria en el
600
         * fichero.
601
         * 
602
         * @param index
603
         *            DOCUMENT ME!
604
         * @param feat
605
         *            DOCUMENT ME!
606
         * 
607
         * @return DOCUMENT ME!
608
         * 
609
         * @throws IOException
610
         * @throws DriverIOException
611
         */
612
        public int doModifyRow(int index, IRow feat, int sourceType)
613
                        throws IOException, DriverIOException {
614
                boolean cancel = fireBeforeModifyRow(feat, index, sourceType);
615
                if (cancel)
616
                        return -1;
617

    
618
                int pos = -1;
619
                Integer integer = new Integer(index);
620
                System.err.println("Modifica una Row en la posici?n: " + index);
621
                // Si la geometr?a no ha sido modificada
622
                if (!relations.containsKey(integer)) {
623
                        int expansionIndex = expansionFile.addRow(feat,
624
                                        IRowEdited.STATUS_MODIFIED, actualIndexFields);
625
                        relations.put(integer, new Integer(expansionIndex));
626
                } else {
627
                        // Obtenemos el ?ndice en el fichero de expansi?n
628
                        int num = ((Integer) relations.get(integer)).intValue();
629
                        pos = num;
630

    
631
                        /*
632
                         * Se modifica la geometr?a y nos guardamos el ?ndice dentro del
633
                         * fichero de expansi?n en el que se encuentra la geometr?a
634
                         * modificada
635
                         */
636
                        num = expansionFile.modifyRow(num, feat, actualIndexFields);
637

    
638
                        /*
639
                         * Actualiza la relaci?n del ?ndice de la geometr?a al ?ndice en el
640
                         * fichero de expansi?n.
641
                         */
642
                        relations.put(integer, new Integer(num));
643
                }
644
                fireAfterModifyRow(index, sourceType);
645
                return pos;
646
        }
647

    
648
        /**
649
         * A?ade una geometria al fichero de expansi?n y guarda la correspondencia
650
         * en la tabla relations.
651
         * 
652
         * @param feat
653
         *            geometr?a a guardar.
654
         * 
655
         * @return calculatedIndex
656
         * 
657
         * @throws DriverIOException
658
         * @throws IOException
659
         */
660
        public int doAddRow(IRow feat, int sourceType) throws DriverIOException,
661
                        IOException {
662
                boolean cancel = fireBeforeRowAdded(sourceType);
663
                if (cancel)
664
                        return -1;
665
                // A?ade la geometr?a
666
                // int virtualIndex = 0;
667
                int calculatedIndex = -1;
668

    
669
                try {
670
                        calculatedIndex = (int) ods.getRowCount() + numAdd;
671
                        // int externalIndex = getRowCount();
672
                        // calculatedIndex = getCalculatedIndex(externalIndex);
673
                } catch (DriverException e) {
674
                        throw new DriverIOException(e);
675
                }
676

    
677
                int pos = expansionFile.addRow(feat, IRowEdited.STATUS_ADDED, actualIndexFields);
678
                relations.put(new Integer(calculatedIndex), new Integer(pos));
679
                numAdd++;
680
                System.err.println("A?ade una Row en la posici?n: " + calculatedIndex);
681
                fireAfterRowAdded(calculatedIndex, sourceType);
682
                return calculatedIndex;
683
        }
684

    
685
        /**
686
         * Se desmarca como invalidada en el fichero de expansion o como eliminada
687
         * en el fichero original
688
         * 
689
         * @param index
690
         *            DOCUMENT ME!
691
         * 
692
         * @throws IOException
693
         * @throws DriverIOException
694
         */
695
        public void undoRemoveRow(int index, int sourceType) throws IOException,
696
                        DriverIOException {
697
                boolean cancel = fireBeforeRowAdded(sourceType);
698
                if (cancel)
699
                        return;
700
                delRows.set(index, false);
701
                fireAfterRowAdded(index, sourceType);
702
        }
703

    
704
        /**
705
         * Se elimina del final del fichero de expansi?n poniendo el puntero de
706
         * escritura apuntando al final de la pen?ltima geometr?a. Deber? quitar la
707
         * relaci?n del mapa de relaciones
708
         * 
709
         * @param index
710
         *            ?ndice de la geometr?a que se a?adi?
711
         * 
712
         * @throws DriverIOException
713
         * @throws IOException
714
         */
715
        public void undoAddRow(int calculatedIndex, int sourceType)
716
                        throws DriverIOException, IOException {
717
                boolean cancel = fireBeforeRemoveRow(calculatedIndex, sourceType);
718
                if (cancel)
719
                        return;
720
                expansionFile.deleteLastRow();
721
                relations.remove(new Integer(calculatedIndex));
722
                numAdd--;
723
                fireAfterRemoveRow(calculatedIndex, sourceType);
724
        }
725

    
726
        /*
727
         * (non-Javadoc)
728
         * 
729
         * @see com.iver.cit.gvsig.fmap.layers.VectorialAdapter#getRecordset()
730
         */
731
        public SelectableDataSource getRecordset() throws DriverLoadException {
732
                if (isEditing) {
733
                        if (ds == null) {
734
                                String name = LayerFactory.getDataSourceFactory()
735
                                                .addDataSource((ObjectDriver) editingDriver);
736

    
737
                                try {
738
                                        ds = new SelectableDataSource(LayerFactory
739
                                                        .getDataSourceFactory().createRandomDataSource(
740
                                                                        name, DataSourceFactory.MANUAL_OPENING));
741
                                        ds.start();
742
                                        ds.setSelectionSupport(ods.getSelectionSupport());
743

    
744
                                } catch (NoSuchTableException e) {
745
                                        throw new RuntimeException(e);
746
                                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
747
                                        throw new RuntimeException(e);
748
                                }
749
                        }
750

    
751
                        return ds;
752
                } else {
753
                        return ods;
754
                }
755
        }
756

    
757

    
758
        /**
759
         * DOCUMENT ME!
760
         * 
761
         * @return
762
         */
763
        public FBitSet getSelection() {
764
                /*
765
                 * try { return getRecordset().getSelection(); } catch
766
                 * (DriverLoadException e) { // TODO Auto-generated catch block
767
                 * e.printStackTrace(); } return null;
768
                 */
769
                return getRecordset().getSelection();
770
        }
771

    
772
        public void setSelection(FBitSet selection) {
773
                /*
774
                 * try { getRecordset().setSelection(selection); } catch
775
                 * (DriverLoadException e) { // TODO Auto-generated catch block
776
                 * e.printStackTrace(); }
777
                 */
778
                getRecordset().setSelection(selection);
779
        }
780

    
781
        /**
782
         * DOCUMENT ME!
783
         * 
784
         * @return DOCUMENT ME!
785
         */
786
        public boolean isEditing() {
787
                return isEditing;
788
        }
789

    
790
        public int getInversedIndex(long rowIndex) {
791
                int intervalNotDeleted = 0;
792
                int antDeleted = -1;
793
                int idPedido = (int) rowIndex;
794
                int numNotDeleted = 0;
795
                int numBorradosAnt = 0;
796

    
797
                for (int i = delRows.nextSetBit(0); i >= 0; i = delRows
798
                                .nextSetBit(i + 1)) {
799
                        intervalNotDeleted = i - antDeleted - 1;
800
                        numNotDeleted += intervalNotDeleted;
801
                        if (i > idPedido) {
802
                                numNotDeleted = numNotDeleted + (i - idPedido);
803
                                break;
804
                        }
805
                        numBorradosAnt++;
806
                        antDeleted = i;
807
                }
808
                numNotDeleted = idPedido - numBorradosAnt;
809
                // System.out.println("Piden Viejo : "+ rowIndex + " y devuelvo como
810
                // nuevo " + (numNotDeleted));
811
                return numNotDeleted;
812
        }
813

    
814
        /**
815
         * DOCUMENT ME!
816
         * 
817
         * @param rowIndex
818
         *            DOCUMENT ME!
819
         * 
820
         * @return DOCUMENT ME!
821
         */
822
        public int getCalculatedIndex(long rowIndex) {
823
                int numNotDeleted = 0;
824
                int intervalNotDeleted = 0;
825
                int antDeleted = -1;
826
                int calculatedIndex;
827
                int idPedido = (int) rowIndex;
828
                int numBorradosAnt = 0;
829

    
830
                for (int i = delRows.nextSetBit(0); i >= 0; i = delRows
831
                                .nextSetBit(i + 1)) {
832
                        intervalNotDeleted = i - antDeleted - 1;
833
                        numNotDeleted += intervalNotDeleted;
834
                        if (numNotDeleted > idPedido) {
835
                                break;
836
                        }
837
                        numBorradosAnt++;
838
                        antDeleted = i;
839
                }
840
                calculatedIndex = numBorradosAnt + idPedido;
841
                // System.out.println("Piden Registro : "+ rowIndex + " y devuelvo el "
842
                // + (calculatedIndex));
843
                return calculatedIndex;
844
        }
845

    
846
        /**
847
         * DOCUMENT ME!
848
         * 
849
         * @author Vicente Caballero Navarro
850
         */
851
        private class myObjectDriver implements ObjectDriver {
852
                /*
853
                 * (non-Javadoc)
854
                 * 
855
                 * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#getPrimaryKeys()
856
                 */
857
                public int[] getPrimaryKeys() throws DriverException {
858
                        return ods.getPrimaryKeys();
859
                        // int[] pk=new int[1];
860
                        /*
861
                         * for (int i=0;i<getRowCount();i++){ pk[i]=i; }
862
                         */
863
                        // pk[0]=1;
864
                        // return pk;
865
                }
866

    
867
                /*
868
                 * (non-Javadoc)
869
                 * 
870
                 * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#write(com.hardcode.gdbms.engine.data.edition.DataWare)
871
                 */
872
                public void write(DataWare dataWare) throws DriverException {
873
                        DataWare dataWareOrig = ods
874
                                        .getDataWare(DataSourceFactory.DATA_WARE_DIRECT_MODE);
875
                        dataWareOrig.commitTrans();
876
                }
877

    
878
                /*
879
                 * (non-Javadoc)
880
                 * 
881
                 * @see com.hardcode.gdbms.engine.data.driver.GDBMSDriver#setDataSourceFactory(com.hardcode.gdbms.engine.data.DataSourceFactory)
882
                 */
883
                public void setDataSourceFactory(DataSourceFactory dsf) {
884
                        ods.setDataSourceFactory(dsf);
885
                }
886

    
887
                /*
888
                 * (non-Javadoc)
889
                 * 
890
                 * @see com.hardcode.driverManager.Driver#getName()
891
                 */
892
                public String getName() {
893
                        return ods.getName();
894
                }
895

    
896
                /*
897
                 * (non-Javadoc)
898
                 * 
899
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldValue(long,
900
                 *      int)
901
                 */
902
                public Value getFieldValue(long rowIndex, int fieldId)
903
                                throws DriverException {
904
                        // Si no est? en el fichero de expansi?n
905
                        // Integer integer = new Integer(getCalculatedIndex(rowIndex));
906

    
907

    
908
                        try {
909
                                IRow row = getRow((int)rowIndex);
910
                                return row.getAttribute(fieldId);
911
//                                if (!relations.containsKey(integer)) {
912
//                                        return ods.getFieldValue(rowIndex, fieldId);
913
//                                } else {
914
//                                        int num = ((Integer) relations.get(integer)).intValue();
915
//                                        DefaultRowEdited feat = (DefaultRowEdited) expansionFile
916
//                                                        .getRow(num);
917
//
918
//                                        if (feat == null) {
919
//                                                return null;
920
//                                        }
921
//
922
//                                        return feat.getAttribute(fieldId);
923
//                                }
924
//                        } catch (DriverException e) {
925
//                                e.printStackTrace();
926
//                                throw new DriverException(e);
927
                        } catch (IOException e) {
928
                                e.printStackTrace();
929
                                throw new DriverException(e);
930
                        } catch (DriverIOException e) {
931
                                e.printStackTrace();
932
                                throw new DriverException(e);
933
                        }
934

    
935
                        /**
936
                         * try { if (!relations.containsKey(integer)) { // Si ha sido
937
                         * eliminada if (delRows.get(integer.intValue())) { return null; }
938
                         * else { return ods.getFieldValue(rowIndex, fieldId); }} else { int
939
                         * num = ((Integer) relations.get(integer)).intValue();
940
                         * DefaultRowEdited feat = (DefaultRowEdited)
941
                         * expansionFile.getRow(num); if (feat==null)return null; return
942
                         * feat.getAttribute(fieldId); }} catch (DriverException e) {
943
                         * e.printStackTrace(); throw new DriverException(e); } catch
944
                         * (IOException e) { e.printStackTrace(); throw new
945
                         * DriverException(e); }
946
                         */
947
                }
948

    
949
                /*
950
                 * (non-Javadoc)
951
                 * 
952
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldCount()
953
                 */
954
                public int getFieldCount() throws DriverException {
955
                        return actualFields.size();
956
                }
957

    
958
                /*
959
                 * (non-Javadoc)
960
                 * 
961
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldName(int)
962
                 */
963
                public String getFieldName(int fieldId) throws DriverException {
964
                        
965
                        for (Iterator iter = actualFields.values().iterator(); iter.hasNext();) {
966
                                InternalField fld = (InternalField) iter.next();
967
                                if (fld.getFieldIndex() == fieldId)
968
                                        return fld.getFieldDesc().getFieldAlias();
969
                                
970
                        }
971
                        throw new DriverException("FieldId " + fieldId + " not found ");
972
                        // return null;
973
                        // return ods.getFieldName(fieldId);
974
                }
975

    
976
                /*
977
                 * (non-Javadoc)
978
                 * 
979
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getRowCount()
980
                 */
981
                public long getRowCount() {
982
                        try {
983
                                return (int) (ods.getRowCount() + numAdd)
984
                                                - delRows.cardinality();// -
985
                                // expansionFile.getInvalidRows().cardinality();
986
                        } catch (DriverException e) {
987
                                // TODO Auto-generated catch block
988
                                e.printStackTrace();
989
                        }
990

    
991
                        return 0;
992
                }
993

    
994
                /*
995
                 * (non-Javadoc)
996
                 * 
997
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldType(int)
998
                 */
999
                public int getFieldType(int i) throws DriverException {
1000
                        for (Iterator iter = actualFields.values().iterator(); iter.hasNext();) {
1001
                                InternalField fld = (InternalField) iter.next();
1002
                                if (fld.getFieldIndex() == i)
1003
                                        return fld.getFieldDesc().getFieldType();
1004
                                
1005
                        }
1006
                        
1007
                        return ods.getFieldType(i);
1008
                }
1009

    
1010
                public int getFieldWidth(int i) throws DriverException {
1011
                        for (Iterator iter = actualFields.values().iterator(); iter.hasNext();) {
1012
                                InternalField fld = (InternalField) iter.next();
1013
                                if (fld.getFieldIndex() == i)
1014
                                        return fld.getFieldDesc().getFieldLength();
1015
                                
1016
                        }
1017

    
1018
                        return ods.getFieldWidth(i);
1019
                }
1020

    
1021
                public void reload() throws IOException, DriverException {
1022
                        ods.reload();
1023
                        
1024
                }
1025
        }
1026

    
1027
        public CommandRecord getCommandRecord() {
1028
                return cr;
1029
        }
1030

    
1031
        protected void fireAfterRemoveRow(int index, int sourceType) {
1032
                AfterRowEditEvent event = new AfterRowEditEvent(this, index,
1033
                                EditionEvent.CHANGE_TYPE_DELETE, sourceType);
1034
                for (int i = 0; i < editionListeners.size(); i++) {
1035
                        IEditionListener listener = (IEditionListener) editionListeners
1036
                                        .get(i);
1037
                        listener.afterRowEditEvent(event);
1038
                }
1039

    
1040
        }
1041

    
1042
        protected boolean fireBeforeRemoveRow(int index, int sourceType) {
1043
                Cancel cancel = new Cancel();
1044
                BeforeRowEditEvent event = new BeforeRowEditEvent(this, index,
1045
                                EditionEvent.CHANGE_TYPE_DELETE, cancel, sourceType);
1046
                for (int i = 0; i < editionListeners.size(); i++) {
1047
                        IEditionListener listener = (IEditionListener) editionListeners
1048
                                        .get(i);
1049
                        listener.beforeRowEditEvent(null, event);
1050
                        if (cancel.isCanceled())
1051
                                return true;
1052
                }
1053
                return false;
1054
        }
1055

    
1056
        protected void fireAfterRowAdded(int calculatedIndex, int sourceType) {
1057
                AfterRowEditEvent event = new AfterRowEditEvent(this, calculatedIndex,
1058
                                EditionEvent.CHANGE_TYPE_ADD, sourceType);
1059
                for (int i = 0; i < editionListeners.size(); i++) {
1060
                        IEditionListener listener = (IEditionListener) editionListeners
1061
                                        .get(i);
1062
                        listener.afterRowEditEvent(event);
1063
                }
1064
        }
1065

    
1066
        protected boolean fireBeforeRowAdded(int sourceType)
1067
                        throws DriverIOException, IOException {
1068
                Cancel cancel = new Cancel();
1069
                BeforeRowEditEvent event = new BeforeRowEditEvent(this, getRowCount(),
1070
                                EditionEvent.CHANGE_TYPE_ADD, cancel, sourceType);
1071
                for (int i = 0; i < editionListeners.size(); i++) {
1072
                        IEditionListener listener = (IEditionListener) editionListeners
1073
                                        .get(i);
1074
                        listener.beforeRowEditEvent(null, event);
1075
                        if (cancel.isCanceled())
1076
                                return true;
1077
                }
1078
                return false;
1079
        }
1080

    
1081
        protected boolean fireBeforeModifyRow(IRow feat, int index, int sourceType) {
1082
                Cancel cancel = new Cancel();
1083
                BeforeRowEditEvent event = new BeforeRowEditEvent(this, index,
1084
                                EditionEvent.CHANGE_TYPE_MODIFY, cancel, sourceType);
1085
                for (int i = 0; i < editionListeners.size(); i++) {
1086
                        IEditionListener listener = (IEditionListener) editionListeners
1087
                                        .get(i);
1088
                        listener.beforeRowEditEvent(feat, event);
1089
                        if (cancel.isCanceled())
1090
                                return true;
1091
                }
1092
                return false;
1093
        }
1094

    
1095
        protected void fireAfterModifyRow(int index, int sourceType) {
1096
                AfterRowEditEvent event = new AfterRowEditEvent(this, index,
1097
                                EditionEvent.CHANGE_TYPE_MODIFY, sourceType);
1098
                for (int i = 0; i < editionListeners.size(); i++) {
1099
                        IEditionListener listener = (IEditionListener) editionListeners
1100
                                        .get(i);
1101
                        listener.afterRowEditEvent(event);
1102
                }
1103

    
1104
        }
1105

    
1106
        protected void fireStartEditionEvent(int sourceType) {
1107
                EditionEvent ev = new EditionEvent(this, EditionEvent.START_EDITION,
1108
                                sourceType);
1109
                for (int i = 0; i < editionListeners.size(); i++) {
1110
                        IEditionListener listener = (IEditionListener) editionListeners
1111
                                        .get(i);
1112
                        listener.processEvent(ev);
1113
                }
1114

    
1115
        }
1116

    
1117
        protected void fireStopEditionEvent(int sourceType) {
1118
                EditionEvent ev = new EditionEvent(this, EditionEvent.STOP_EDITION,
1119
                                sourceType);
1120
                for (int i = 0; i < editionListeners.size(); i++) {
1121
                        IEditionListener listener = (IEditionListener) editionListeners
1122
                                        .get(i);
1123
                        listener.processEvent(ev);
1124
                }
1125

    
1126
        }
1127

    
1128
        protected void fireCancelEditionEvent(int sourceType) {
1129
                EditionEvent ev = new EditionEvent(this, EditionEvent.CANCEL_EDITION,
1130
                                sourceType);
1131
                for (int i = 0; i < editionListeners.size(); i++) {
1132
                        IEditionListener listener = (IEditionListener) editionListeners
1133
                                        .get(i);
1134
                        listener.processEvent(ev);
1135
                }
1136

    
1137
        }
1138

    
1139
        public void addEditionListener(IEditionListener listener) {
1140
                if (!editionListeners.contains(listener))
1141
                        editionListeners.add(listener);
1142
        }
1143

    
1144
        public void removeEditionListener(IEditionListener listener) {
1145
                editionListeners.remove(listener);
1146
        }
1147

    
1148
        public IWriter getWriter() {
1149
                return writer;
1150
        }
1151

    
1152
        protected void setWriter(IWriter writer) {
1153
                this.writer = writer;
1154

    
1155
        }
1156

    
1157
        public ITableDefinition getTableDefinition() throws DriverLoadException,
1158
                        DriverException {
1159
                TableDefinition tableDef = new TableDefinition();
1160
                tableDef.setFieldsDesc(getRecordset().getFieldsDescription());
1161
                tableDef.setName(getRecordset().getSourceInfo().name);
1162
                return tableDef;
1163
        }
1164

    
1165
        public void validateRow(IRow row) throws EditionException {
1166
                for (int i = 0; i < rules.size(); i++) {
1167
                        IRule rule = (IRule) rules.get(i);
1168
                        boolean bAux = rule.validate(row);
1169
                        if (bAux == false) {
1170
                                EditionException ex = new EditionException(
1171
                                                "NOT follow the rule: " + rule.getDescription());
1172
                                // TODO: Lanzar una RuleException con datos como el registro
1173
                                // que no cumple, la regla que no lo ha cumplido, etc.
1174
                                throw ex;
1175
                        }
1176
                }
1177
        }
1178

    
1179
        public ArrayList getRules() {
1180
                return rules;
1181
        }
1182

    
1183
        public void setRules(ArrayList rules) {
1184
                this.rules = rules;
1185
        }
1186

    
1187
        private void clean() throws IOException, DriverException {
1188
                expansionFile.close();
1189
                relations.clear();
1190
                numAdd = 0;
1191
                delRows.clear();
1192
                // TODO: Es muy probable que necesitemos un reload de los datasources, al
1193
                // igual que lo tenemos en las capas. Por ahora, basta con retocar
1194
                // listInternalFields, pero casi seguro que lo correcto ser?a hacer un
1195
                // reload completo.
1196
                initalizeFields(ods);
1197
                
1198
//                listInternalFields.clear();
1199
//                listInternalFields.add(actualFields);
1200
        }
1201

    
1202
        /*
1203
         * (non-Javadoc)
1204
         * 
1205
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#getFieldManager()
1206
         */
1207
        public IFieldManager getFieldManager() {
1208
                if (ods.getDriver() instanceof IFieldManager)
1209
                        return (IFieldManager) ods.getDriver();
1210
                return null;
1211
        }
1212

    
1213
        /**
1214
         * Tiene en cuenta los campos actuales para formatear una row con ellos. Le
1215
         * pasamos los campos que hab?a en el momento en que se cre? esa row.
1216
         * 
1217
         * @param edRow
1218
         * @param indexInternalFields
1219
         * @return
1220
         */
1221
        public IRowEdited createExternalRow(IRowEdited edRow,
1222
                        int indexInternalFields) {
1223
                Value[] att = edRow.getAttributes();
1224
                TreeMap ancientFields = (TreeMap) listInternalFields
1225
                                .get(indexInternalFields);
1226
                Value[] newAtt = new Value[actualFields.size()];
1227
                Collection aux = actualFields.values();
1228
                Iterator it = aux.iterator();
1229
                int i = 0;
1230
                Value val = null;
1231
                while (it.hasNext()) {
1232
                        InternalField fld = (InternalField) it.next();
1233
                        System.err.println("fld = " + fld.getFieldDesc().getFieldAlias() + " index=" + fld.getFieldIndex() + " id=" + fld.getFieldId());
1234
                        if (ancientFields.containsKey(fld.getFieldId())) {
1235
                                InternalField ancientField = (InternalField) ancientFields
1236
                                                .get(fld.getFieldId());
1237
                                val = att[ancientField.getFieldIndex()];
1238
                                System.out.println("fld: " + fld.getFieldDesc().getFieldAlias() + " ancient:" + ancientField.getFieldIndex() + " val" + val);
1239
                        } else
1240
                                val = fld.getFieldDesc().getDefaultValue();
1241
                        newAtt[i++] = val;
1242
                }
1243
                IRowEdited newRow = (IRowEdited) edRow.cloneRow();
1244
                newRow.setAttributes(newAtt);
1245
                return newRow;
1246
        }
1247

    
1248
        public void removeField(String fieldName) throws EditionException {
1249

    
1250
                InternalField fld = findFieldByName(fieldName);
1251
                if (fld == null)
1252
                        throw new EditionException("Field " + fieldName + " not found when removing field");
1253
                Command command = new RemoveFieldCommand(this, fld);
1254
                if (complex) {
1255
                        commands.add(command);
1256
                } else {
1257
                        cr.pushCommand(command);
1258
                }
1259
                doRemoveField(fld);
1260

    
1261
        }
1262

    
1263
        private InternalField findFieldByName(String fieldName) {
1264
                Collection aux = actualFields.values();
1265
                Iterator it = aux.iterator();
1266
                while (it.hasNext()) {
1267
                        InternalField fld = (InternalField) it.next();
1268
                        if (fld.getFieldDesc().getFieldName().compareToIgnoreCase(fieldName) == 0)
1269
                                return fld;
1270
                }
1271
                
1272
                return null;
1273
        }
1274

    
1275
        public void undoRemoveField(InternalField field) throws EditionException {
1276
                field.setDeleted(false);
1277
                field.setFieldIndex(actualFields.size());
1278
                actualFields.put(field.getFieldId(), field);
1279
                fieldsChanged();
1280
        }
1281

    
1282
        public void doRemoveField(InternalField field) throws EditionException {
1283
                field.setDeleted(true);
1284
                actualFields.remove(field.getFieldId());
1285
                fieldsChanged();
1286
        }
1287

    
1288
        public void renameField(String antName, String newName) throws EditionException {
1289

    
1290
                InternalField fld = findFieldByName(antName);
1291
                Command command = new RenameFieldCommand(this, fld, newName);
1292
                if (complex) {
1293
                        commands.add(command);
1294
                } else {
1295
                        cr.pushCommand(command);
1296
                }
1297
                doRenameField(fld, newName);
1298

    
1299
        }
1300
        
1301
        public void undoRenameField(InternalField field, String antName) {
1302
                field.getFieldDesc().setFieldAlias(antName);
1303
        }
1304

    
1305
        public void doRenameField(InternalField field, String newName) {
1306
                field.getFieldDesc().setFieldAlias(newName);
1307
        }
1308

    
1309

    
1310
        public void addField(FieldDescription field) throws EditionException {
1311

    
1312
                InternalField fld = new InternalField(field, InternalField.ADDED, new Integer(listFields.size()));
1313
                Command command = new AddFieldCommand(this, fld);
1314
                if (complex) {
1315
                        commands.add(command);
1316
                } else {
1317
                        cr.pushCommand(command);
1318
                }
1319
                listFields.add(fld);
1320
                doAddField(fld);
1321

    
1322
        }
1323

    
1324
        public void undoAddField(InternalField field) throws EditionException {
1325
                field.setDeleted(true);
1326
                
1327
                actualFields.remove(field.getFieldId());
1328
                fieldsChanged();
1329
                
1330
        }
1331

    
1332
        public void doAddField(InternalField field) throws EditionException {
1333
                field.setDeleted(false);
1334
                field.setFieldIndex(actualFields.size());
1335
                actualFields.put(field.getFieldId(), field);
1336
                fieldsChanged();
1337
                
1338
        }
1339
        
1340
}