Statistics
| Revision:

svn-gvsig-desktop / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / edition / EditableAdapter.java @ 6580

History | View | Annotate | Download (44.5 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.drivers.dbf.DBFDriver;
25
import com.iver.cit.gvsig.fmap.edition.commands.AddFieldCommand;
26
import com.iver.cit.gvsig.fmap.edition.commands.AddRowCommand;
27
import com.iver.cit.gvsig.fmap.edition.commands.Command;
28
import com.iver.cit.gvsig.fmap.edition.commands.CommandCollection;
29
import com.iver.cit.gvsig.fmap.edition.commands.CommandRecord;
30
import com.iver.cit.gvsig.fmap.edition.commands.MemoryCommandRecord;
31
import com.iver.cit.gvsig.fmap.edition.commands.ModifyRowCommand;
32
import com.iver.cit.gvsig.fmap.edition.commands.RemoveFieldCommand;
33
import com.iver.cit.gvsig.fmap.edition.commands.RemoveRowCommand;
34
import com.iver.cit.gvsig.fmap.edition.commands.RenameFieldCommand;
35
import com.iver.cit.gvsig.fmap.edition.fieldmanagers.AbstractFieldManager;
36
import com.iver.cit.gvsig.fmap.edition.rules.IRule;
37
import com.iver.cit.gvsig.fmap.layers.FBitSet;
38
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
39
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
40
import com.iver.cit.gvsig.fmap.operations.Cancel;
41

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

    
50
        private SelectableDataSource ds = null;
51

    
52
        protected FBitSet delRows = new FBitSet();
53

    
54
        private CommandRecord cr;
55

    
56
        protected IWriter writer;
57

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

    
64
        private CommandCollection commands = null;
65

    
66
        protected ArrayList listFields = new ArrayList();
67

    
68
        protected ArrayList listInternalFields = new ArrayList();
69
        
70
        protected boolean bFieldsHasBeenChanged = false;
71

    
72
        /**
73
         * La clave ser? el fieldId. Para buscar si un value de una row ha de ser
74
         * rellenado con defaultValue o con lo que venga del expansion file,
75
         * miraremos si existe en este hash. Si existe, usamos el value del
76
         * expansion file. Si no existe, usamos el defaultValue del campo busc?ndolo
77
         * en la lista internalFields. Por cierto, en listInternalFields NO se
78
         * borran campos. Solo se van a?adiendo nuevos actualFields.
79
         */
80
        protected TreeMap actualFields; // la clave ser? el fieldId.
81
        
82
        protected ArrayList fastAccessFields = new ArrayList();
83

    
84
        protected class MyFieldManager extends AbstractFieldManager {
85

    
86
                public boolean alterTable() throws EditionException {
87
                        return getFieldManager().alterTable();
88
                }
89

    
90
                public void addField(FieldDescription fieldDesc) {
91
                        super.addField(fieldDesc);
92
                }
93

    
94
                public FieldDescription removeField(String fieldName) {
95
                        // TODO Auto-generated method stub
96
                        return super.removeField(fieldName);
97
                }
98

    
99
                public void renameField(String antName, String newName) {
100
                        // TODO Auto-generated method stub
101
                        super.renameField(antName, newName);
102
                }
103

    
104
        }
105

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

    
121
        /*
122
         * Fichero en el que se guardan las nuevas geometr?as, producto de adiciones
123
         * o de modificaciones
124
         */
125
        protected ExpansionFile expansionFile;
126

    
127
        protected int numAdd = 0;
128

    
129
        private ObjectDriver editingDriver = new myObjectDriver();
130

    
131
        private SelectableDataSource ods;
132

    
133
        private ArrayList editionListeners = new ArrayList();
134

    
135
        private ArrayList rules = new ArrayList();
136

    
137
        protected int actualIndexFields;
138

    
139
        /**
140
         * Crea un nuevo EditableAdapter.
141
         */
142
        public EditableAdapter() {
143
                expansionFile = new MemoryExpansionFile(this);
144
                cr = new MemoryCommandRecord();
145
        }
146

    
147
        /**
148
         * DOCUMENT ME!
149
         * 
150
         * @param ds
151
         *            DOCUMENT ME!
152
         * @throws DriverException 
153
         */
154
        public void setOriginalDataSource(SelectableDataSource ds) throws DriverException {
155
                this.ods = ds;
156
                initalizeFields(ds);
157
                
158
        }
159

    
160
        /**
161
         * @param ds
162
         * @throws DriverException
163
         */
164
        private void initalizeFields(SelectableDataSource ds) throws DriverException {
165
                FieldDescription[] fields = ds.getFieldsDescription();
166
                listInternalFields.clear();
167
                actualIndexFields = 0;
168
                actualFields = new TreeMap();
169
//                fastAccessFields = new ArrayList();
170
                for (int i=0; i < fields.length; i++)
171
                {
172
                        InternalField field = new InternalField(fields[i], InternalField.ORIGINAL, new Integer(i));
173
                        listFields.add(field);
174
                        // field.setFieldIndex(i);
175
                        actualFields.put(field.getFieldId(), field);
176
//                        fastAccessFields.add(fields[i]);
177
                        System.out.println("INITIALIZEFIELDS: FIELD " + field.getFieldDesc().getFieldAlias());
178
                }
179
                try {
180
                        fieldsChanged();
181
                        bFieldsHasBeenChanged = false;
182
                } catch (EditionException e) {
183
                        e.printStackTrace();
184
                        throw new DriverException(e);
185
                }
186
        }
187

    
188
        private void fieldsChanged() throws EditionException {
189
                fastAccessFields= new ArrayList();
190
                for (Iterator iter = actualFields.values().iterator(); iter.hasNext();) {
191
                        InternalField fld = (InternalField) iter.next();
192
                        fastAccessFields.add(fld.getFieldDesc());
193
                }
194

    
195
                listInternalFields.add(actualFields.clone());
196
                actualIndexFields = listInternalFields.size()-1;
197
                try {
198
                        ds = null;
199
                        getRecordset().mapExternalFields();
200
                        bFieldsHasBeenChanged = true;
201
                } catch (DriverLoadException e) {
202
                        e.printStackTrace();
203
                        throw new EditionException(e);
204
                } catch (DriverException e) {
205
                        e.printStackTrace();
206
                        throw new EditionException(e);
207
                }
208
        }
209

    
210
        /**
211
         * DOCUMENT ME!
212
         * 
213
         * @throws EditionException
214
         *             DOCUMENT ME!
215
         */
216
        public void startEdition(int sourceType) throws EditionException {
217
                isEditing = true;
218
                // Obtenemos el driver y vemos si implementa IWriter.
219
                /*
220
                 * DataWare dataWare =
221
                 * ods.getDataWare(DataSourceFactory.DATA_WARE_DIRECT_MODE);
222
                 * dataWare.get
223
                 */
224
                Driver drv = ods.getDriver();
225
                if (drv instanceof IWriteable) {
226
                        setWriter(((IWriteable) drv).getWriter());
227
                }
228

    
229
                fireStartEditionEvent(sourceType);
230
        }
231

    
232
        /**
233
         * Se ejecuta preProcess() del IWriter, luego se itera por los registros
234
         * borrados por si el IWriter los quiere borrar (solo ser? necesario cuando
235
         * escribimos sobre la misma tabla) y luego se itera por los nuevos
236
         * registros llamando a process con el registro correcto. (A?adidos,
237
         * modificados). Para finalizar, se ejecuta PostProcess
238
         * 
239
         * @param writer
240
         *            IWriter que recibir? las llamadas.
241
         * 
242
         * @throws EditionException
243
         *             DOCUMENT ME!
244
         */
245
        public void stopEdition(IWriter writer, int sourceType)
246
                        throws EditionException {
247
                saveEdits(writer, sourceType);
248
                isEditing = false;
249
                cr.clearAll();
250
                fireStopEditionEvent(sourceType);
251
        }
252

    
253
        public void saveEdits(IWriter writer, int sourceType)
254
                        throws EditionException {
255
                
256
                // TODO: ARREGLAR ESTO PARA QUE CUANDO HA HABIDO CAMBIOS
257
                // EN LOS CAMPOS, PODAMOS CAMBIAR LO QUE TOQUE (A SER POSIBLE
258
                // SIN TENER QUE REESCRIBIR TODA LA TABLA CON POSTGIS)
259
                if (bFieldsHasBeenChanged)
260
                {
261
                        // Para cada campo de los originales, miramos si no est? en 
262
                        // los actuales. Si no est?, le decimos al fieldManager
263
                        // que lo borre. Si est?, pero le hemos cambiado el nombre
264
                        // le pedimos al fieldManager que le cambie el nombre.
265
                        // Luego recorremos los campos actuales para ver cuales
266
                        // son nuevos, y los a?adimos.
267
 
268
                        TreeMap ancientFields = (TreeMap) listInternalFields
269
                                        .get(0);
270
                        Collection aux = ancientFields.values();
271
                        Iterator it = aux.iterator();
272
                        while (it.hasNext()) {
273
                                InternalField fld = (InternalField) it.next();
274
                                // System.err.println("fld = " + fld.getFieldDesc().getFieldAlias() +  " id=" + fld.getFieldId());
275
                                if (actualFields.containsKey(fld.getFieldId())) {
276
                                        // Es un original
277
                                        String f1 = fld.getFieldDesc().getFieldName();
278
                                        String f2 = fld.getFieldDesc().getFieldAlias();
279
                                        if (f1.compareTo(f2) != 0)
280
                                        {
281
                                                getFieldManager().renameField(f1, f2);
282
                                        }        
283
                                }
284
                                else
285
                                {        // No est?, hay que borrarlo
286
                                        getFieldManager().removeField(fld.getFieldDesc().getFieldAlias());
287
                                }
288
                        }
289
                        Collection aux2= actualFields.values();
290
                        Iterator it2 = aux2.iterator();
291
                        while (it2.hasNext()) {
292
                                InternalField fld = (InternalField) it2.next();
293
                                // System.err.println("fld = " + fld.getFieldDesc().getFieldAlias() +  " id=" + fld.getFieldId());
294
                                if (!ancientFields.containsKey(fld.getFieldId())) {
295
                                        // Es uno a?adido
296
                                        getFieldManager().addField(fld.getFieldDesc());
297
                                }
298
                        }
299
                        // getFieldManager().alterTable(); // Se llama dentro del preprocess()
300
                }
301
                
302
                writer.preProcess();
303

    
304
                try {
305

    
306
                        // Procesamos primero los borrados.
307
                        // Cuando se genere un tema nuevo, no se les debe hacer caso
308
                        // a estos registros
309

    
310
                        for (int i = delRows.nextSetBit(0); i >= 0; i = delRows
311
                                        .nextSetBit(i + 1)) {
312
                                int calculatedIndex = i;
313
                                Integer integer = new Integer(calculatedIndex);
314
                                // Si no est? en el fichero de expansi?n, es de los originales
315
                                // y hay que borrarlo
316
                                DefaultRowEdited edRow = null;
317
                                if (!relations.containsKey(integer)) {
318
                                        edRow = new DefaultRowEdited(new DefaultRow(ods
319
                                                        .getRow(calculatedIndex)),
320
                                                        DefaultRowEdited.STATUS_DELETED, calculatedIndex);
321
                                        writer.process(edRow);
322
                                } else {
323
                                        int num = ((Integer) relations.get(integer)).intValue();
324

    
325
                                        // return expansionFile.getRow(num);
326
                                        IRowEdited rowFromExpansion = expansionFile.getRow(num);
327
                                        // ?Habr?a que hacer aqu? setID(index + "")?
328
                                        edRow = new DefaultRowEdited(rowFromExpansion
329
                                                        .getLinkedRow().cloneRow(),
330
                                                        DefaultRowEdited.STATUS_DELETED, calculatedIndex);
331
                                        writer.process(edRow);
332
                                }
333

    
334
                        }
335

    
336
                        int rowCount = getRowCount();
337
                        for (int i = 0; i < rowCount; i++) {
338
                                IRowEdited rowEdited = getRow(i);
339

    
340
                                if (rowEdited != null) {
341
                                        writer.process(rowEdited);
342
                                }
343
                        }
344
                        writer.postProcess();
345

    
346
                        // Hacemos que el escritor se entere de los nuevos campos
347
                        // que tiene. El escritor debe guardar una referencia
348
                        // a los campos con los que trabaja el drier, de forma
349
                        // que al recargar la capa (por ejemplo en el caso de
350
                        // PostGIS, se haga un setData con los campos que se hayan
351
                        // a?adido, borrado o renombrado).
352
                        writer.getTableDefinition().setFieldsDesc(getRecordset().getFieldsDescription());
353

    
354
                        ods.reload();
355
                        ds = null;
356
                        clean();
357
                        
358
                } catch (DriverIOException e) {
359
                        e.printStackTrace();
360
                        throw new EditionException(e);
361
                } catch (IOException e) {
362
                        e.printStackTrace();
363
                        throw new EditionException(e);
364
                } catch (DriverException e) {
365
                        e.printStackTrace();
366
                        throw new EditionException(e);
367
                }
368

    
369
        }
370

    
371
        /**
372
         * DOCUMENT ME!
373
         * 
374
         * @throws IOException
375
         *             DOCUMENT ME!
376
         */
377
        public void cancelEdition(int sourceType) throws IOException {
378
                isEditing = false;
379
                try {
380
                        ds= null;
381
                        clean();
382
                        cr.clearAll();
383
                } catch (DriverException e) {
384
                        e.printStackTrace();
385
                        throw new IOException("Error: " + e.getMessage());
386
                }
387
                fireCancelEditionEvent(sourceType);
388
        }
389

    
390
        /*
391
         * (non-Javadoc)
392
         * 
393
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#getRow(int)
394
         */
395
        public IRowEdited getRow(int index) throws DriverIOException, IOException {
396
                int calculatedIndex = getCalculatedIndex(index);
397
                Integer integer = new Integer(calculatedIndex);
398
                DefaultRowEdited edRow = null;
399
                // Si no est? en el fichero de expansi?n
400
                if (!relations.containsKey(integer)) {
401
                        try {
402
                                /*
403
                                 * edRow = new DefaultRowEdited(new
404
                                 * DefaultRow(ods.getRow(calculatedIndex), "" + index),
405
                                 * DefaultRowEdited.STATUS_ORIGINAL, index);
406
                                 */
407
                                DefaultRow auxR = new DefaultRow(ods.getRow(calculatedIndex));
408
                                edRow = new DefaultRowEdited(auxR,
409
                                                DefaultRowEdited.STATUS_ORIGINAL, index);
410
                                return createExternalRow(edRow, 0);
411
//                                edRow = new DefaultRowEdited(new DefaultRow(ods
412
//                                                .getRow(calculatedIndex)),
413
//                                                DefaultRowEdited.STATUS_ORIGINAL, index);
414
                        } catch (DriverException e) {
415
                                throw new DriverIOException(e);
416
                        }
417
                } else {
418
                        int num = ((Integer) relations.get(integer)).intValue();
419

    
420
                        // return expansionFile.getRow(num);
421
                        // ExpansionFile ya entrega el registro formateado como debe
422
                        IRowEdited rowFromExpansion = expansionFile.getRow(num);
423
                        // ?Habr?a que hacer aqu? setID(index + "")?
424
                        edRow = new DefaultRowEdited(rowFromExpansion.getLinkedRow()
425
                                        .cloneRow(), rowFromExpansion.getStatus(), index);
426
                        return edRow;
427
                }
428
                
429
                
430

    
431
        }
432

    
433
        /**
434
         * DOCUMENT ME!
435
         * 
436
         * @return DOCUMENT ME!
437
         * 
438
         * @throws DriverIOException
439
         *             DOCUMENT ME!
440
         * @throws IOException
441
         *             DOCUMENT ME!
442
         */
443
        public int getRowCount() throws DriverIOException, IOException {
444
                try {
445
                        return (int) (ods.getRowCount() + numAdd) - delRows.cardinality();// -
446
                        // expansionFile.getInvalidRows().cardinality();
447
                } catch (DriverException e) {
448
                        throw new DriverIOException(e);
449
                }
450

    
451
        }
452

    
453
        /*
454
         * (non-Javadoc)
455
         * 
456
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#addRow(com.iver.cit.gvsig.fmap.core.IRow,
457
         *      java.lang.String)
458
         */
459
        public int addRow(IRow row, String descrip, int sourceType)
460
                        throws DriverIOException, IOException {
461

    
462
                try {
463
                        validateRow(row);
464
                } catch (EditionException e) {
465
                        e.printStackTrace();
466
                        throw new IOException(e.getMessage());
467
                }
468

    
469
                int calculatedIndex = doAddRow(row, sourceType);
470
                Command command = new AddRowCommand(this, row, calculatedIndex,
471
                                sourceType);
472
                command.setDescription(descrip);
473
                if (complex) {
474
                        commands.add(command);
475
                } else {
476
                        cr.pushCommand(command);
477
                }
478

    
479
                return calculatedIndex;
480
        }
481

    
482
        /**
483
         * DOCUMENT ME!
484
         * 
485
         * @throws DriverIOException
486
         *             DOCUMENT ME!
487
         * @throws IOException
488
         *             DOCUMENT ME!
489
         */
490
        public void undo() throws DriverIOException, IOException {
491
                // seleccion.clear();
492
                if (cr.moreUndoCommands()) {
493
                        cr.undoCommand();
494
                }
495
        }
496

    
497
        /**
498
         * DOCUMENT ME!
499
         * 
500
         * @throws DriverIOException
501
         *             DOCUMENT ME!
502
         * @throws IOException
503
         *             DOCUMENT ME!
504
         */
505
        public void redo() throws DriverIOException, IOException {
506
                // seleccion.clear();
507
                if (cr.moreRedoCommands()) {
508
                        cr.redoCommand();
509
                }
510
        }
511

    
512
        /*
513
         * (non-Javadoc)
514
         * 
515
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#removeRow(int)
516
         */
517
        public void removeRow(int index, String descrip, int sourceType)
518
                        throws IOException, DriverIOException {
519

    
520
                int calculatedIndex = getCalculatedIndex(index);
521
                Command command = new RemoveRowCommand(this, calculatedIndex,
522
                                sourceType);
523
                command.setDescription(descrip);
524
                if (complex) {
525
                        commands.add(command);
526
                } else {
527
                        cr.pushCommand(command);
528
                }
529
                doRemoveRow(calculatedIndex, sourceType);
530

    
531
        }
532

    
533
        /*
534
         * (non-Javadoc)
535
         * 
536
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#modifyRow(int,
537
         *      com.iver.cit.gvsig.fmap.core.IRow)
538
         */
539
        public int modifyRow(int index, IRow row, String descrip, int sourceType)
540
                        throws IOException, DriverIOException {
541

    
542
                try {
543
                        validateRow(row);
544
                } catch (EditionException e) {
545
                        e.printStackTrace();
546
                        throw new IOException(e.getMessage());
547
                }
548

    
549
                int calculatedIndex = getCalculatedIndex(index);
550
                int pos = doModifyRow(calculatedIndex, row, sourceType);
551
                Command command = new ModifyRowCommand(this, calculatedIndex, pos, row,
552
                                sourceType);
553
                command.setDescription(descrip);
554
                if (complex) {
555
                        commands.add(command);
556
                } else {
557
                        cr.pushCommand(command);
558
                }
559

    
560
                return pos;
561
        }
562

    
563
        /**
564
         * DOCUMENT ME!
565
         */
566
        public void compact() {
567
                expansionFile.compact(relations);
568
        }
569

    
570
        /**
571
         * DOCUMENT ME!
572
         */
573
        public void startComplexRow() {
574
                complex = true;
575
                commands = new CommandCollection();
576
        }
577

    
578
        /**
579
         * DOCUMENT ME!
580
         * 
581
         * @throws IOException
582
         *             DOCUMENT ME!
583
         * @throws DriverIOException
584
         *             DOCUMENT ME!
585
         */
586
        public void endComplexRow(String description) throws IOException,
587
                        DriverIOException {
588
                commands.setDescription(description);
589
                cr.pushCommand(commands);
590
                complex = false;
591
        }
592

    
593
        /**
594
         * Actualiza en el mapa de ?ndices, la posici?n en la que estaba la
595
         * geometr?a antes de ser modificada. Se marca como v?lida, en caso de que
596
         * fuera una modificaci?n de una geometr?a que estuviese en el fichero de
597
         * expansi?n antes de ser modificada y se pone el puntero de escritura del
598
         * expansion file a justo despues de la penultima geometr?a
599
         * 
600
         * @param geometryIndex
601
         *            ?ndice de la geometr?a que se quiere deshacer su modificaci?n
602
         * @param previousExpansionFileIndex
603
         *            ?ndice que ten?a antes la geometr?a en el expansionFile. Si
604
         *            vale -1 quiere decir que es una modificaci?n de una geometr?a
605
         *            original y por tanto no hay que actualizar el mapa de indices
606
         *            sino eliminar su entrada.
607
         * 
608
         * @throws IOException
609
         * @throws DriverIOException
610
         */
611
        public void undoModifyRow(int geometryIndex,
612
                        int previousExpansionFileIndex, int sourceType) throws IOException,
613
                        DriverIOException {
614

    
615
                if (previousExpansionFileIndex == -1) {
616
                        DefaultRowEdited edRow = null;
617
                        try {
618
                                edRow = new DefaultRowEdited(new DefaultRow(ods
619
                                                .getRow(geometryIndex)),
620
                                                DefaultRowEdited.STATUS_ORIGINAL, geometryIndex);
621
                        } catch (DriverException e) {
622
                                e.printStackTrace();
623
                        }
624
                        boolean cancel = fireBeforeModifyRow(edRow, geometryIndex,
625
                                        sourceType);
626
                        if (cancel)
627
                                return;
628
                        // Se elimina de las relaciones y del fichero de expansi?n
629
                        relations.remove(new Integer(geometryIndex));
630
                        expansionFile.deleteLastRow();
631
                } else {
632
                        boolean cancel = fireBeforeModifyRow(expansionFile
633
                                        .getRow(previousExpansionFileIndex), geometryIndex,
634
                                        sourceType);
635
                        if (cancel)
636
                                return;
637
                        // Se actualiza la relaci?n de ?ndices
638
                        relations.put(new Integer(geometryIndex), new Integer(
639
                                        previousExpansionFileIndex));
640
                }
641
                fireAfterModifyRow(geometryIndex, sourceType);
642
        }
643

    
644
        /**
645
         * Elimina una geometria. Si es una geometr?a original de la capa en edici?n
646
         * se marca como eliminada (haya sido modificada o no). Si es una geometr?a
647
         * a?adida posteriormente se invalida en el fichero de expansi?n, para que
648
         * una futura compactaci?n termine con ella.
649
         * 
650
         * @param index
651
         *            ?ndice de la geometr?a.
652
         * 
653
         * @throws DriverIOException
654
         * @throws IOException
655
         */
656
        public IRow doRemoveRow(int index, int sourceType)
657
                        throws DriverIOException, IOException {
658
                boolean cancel = fireBeforeRemoveRow(index, sourceType);
659
                if (cancel)
660
                        return null;
661
                // Llega un calculatedIndex
662
                delRows.set(index, true);
663
                System.err.println("Elimina una Row en la posici?n: " + index);
664
                // TODO: Con tablas no es necesario devolver la anterior feature. Por
665
                // ahora.
666
                fireAfterRemoveRow(index, sourceType);
667
                return null;
668
        }
669

    
670
        /**
671
         * Si se intenta modificar una geometr?a original de la capa en edici?n se
672
         * a?ade al fichero de expansi?n y se registra la posici?n en la que se
673
         * a?adi?. Si se intenta modificar una geometria que se encuentra en el
674
         * fichero de expansi?n (por ser nueva o original pero modificada) se invoca
675
         * el m?todo modifyGeometry y se actualiza el ?ndice de la geometria en el
676
         * fichero.
677
         * 
678
         * @param index
679
         *            DOCUMENT ME!
680
         * @param feat
681
         *            DOCUMENT ME!
682
         * 
683
         * @return DOCUMENT ME!
684
         * 
685
         * @throws IOException
686
         * @throws DriverIOException
687
         */
688
        public int doModifyRow(int index, IRow feat, int sourceType)
689
                        throws IOException, DriverIOException {
690
                boolean cancel = fireBeforeModifyRow(feat, index, sourceType);
691
                if (cancel)
692
                        return -1;
693

    
694
                int pos = -1;
695
                Integer integer = new Integer(index);
696
                System.err.println("Modifica una Row en la posici?n: " + index);
697
                // Si la geometr?a no ha sido modificada
698
                if (!relations.containsKey(integer)) {
699
                        int expansionIndex = expansionFile.addRow(feat,
700
                                        IRowEdited.STATUS_MODIFIED, actualIndexFields);
701
                        relations.put(integer, new Integer(expansionIndex));
702
                } else {
703
                        // Obtenemos el ?ndice en el fichero de expansi?n
704
                        int num = ((Integer) relations.get(integer)).intValue();
705
                        pos = num;
706

    
707
                        /*
708
                         * Se modifica la geometr?a y nos guardamos el ?ndice dentro del
709
                         * fichero de expansi?n en el que se encuentra la geometr?a
710
                         * modificada
711
                         */
712
                        num = expansionFile.modifyRow(num, feat, actualIndexFields);
713

    
714
                        /*
715
                         * Actualiza la relaci?n del ?ndice de la geometr?a al ?ndice en el
716
                         * fichero de expansi?n.
717
                         */
718
                        relations.put(integer, new Integer(num));
719
                }
720
                fireAfterModifyRow(index, sourceType);
721
                return pos;
722
        }
723

    
724
        /**
725
         * A?ade una geometria al fichero de expansi?n y guarda la correspondencia
726
         * en la tabla relations.
727
         * 
728
         * @param feat
729
         *            geometr?a a guardar.
730
         * 
731
         * @return calculatedIndex
732
         * 
733
         * @throws DriverIOException
734
         * @throws IOException
735
         */
736
        public int doAddRow(IRow feat, int sourceType) throws DriverIOException,
737
                        IOException {
738
                boolean cancel = fireBeforeRowAdded(sourceType);
739
                if (cancel)
740
                        return -1;
741
                // A?ade la geometr?a
742
                // int virtualIndex = 0;
743
                int calculatedIndex = -1;
744

    
745
                try {
746
                        calculatedIndex = (int) ods.getRowCount() + numAdd;
747
                        // int externalIndex = getRowCount();
748
                        // calculatedIndex = getCalculatedIndex(externalIndex);
749
                } catch (DriverException e) {
750
                        throw new DriverIOException(e);
751
                }
752

    
753
                int pos = expansionFile.addRow(feat, IRowEdited.STATUS_ADDED, actualIndexFields);
754
                relations.put(new Integer(calculatedIndex), new Integer(pos));
755
                numAdd++;
756
                System.err.println("A?ade una Row en la posici?n: " + calculatedIndex);
757
                fireAfterRowAdded(calculatedIndex, sourceType);
758
                return calculatedIndex;
759
        }
760

    
761
        /**
762
         * Se desmarca como invalidada en el fichero de expansion o como eliminada
763
         * en el fichero original
764
         * 
765
         * @param index
766
         *            DOCUMENT ME!
767
         * 
768
         * @throws IOException
769
         * @throws DriverIOException
770
         */
771
        public void undoRemoveRow(int index, int sourceType) throws IOException,
772
                        DriverIOException {
773
                boolean cancel = fireBeforeRowAdded(sourceType);
774
                if (cancel)
775
                        return;
776
                delRows.set(index, false);
777
                fireAfterRowAdded(index, sourceType);
778
        }
779

    
780
        /**
781
         * Se elimina del final del fichero de expansi?n poniendo el puntero de
782
         * escritura apuntando al final de la pen?ltima geometr?a. Deber? quitar la
783
         * relaci?n del mapa de relaciones
784
         * 
785
         * @param index
786
         *            ?ndice de la geometr?a que se a?adi?
787
         * 
788
         * @throws DriverIOException
789
         * @throws IOException
790
         */
791
        public void undoAddRow(int calculatedIndex, int sourceType)
792
                        throws DriverIOException, IOException {
793
                boolean cancel = fireBeforeRemoveRow(calculatedIndex, sourceType);
794
                if (cancel)
795
                        return;
796
                expansionFile.deleteLastRow();
797
                relations.remove(new Integer(calculatedIndex));
798
                numAdd--;
799
                fireAfterRemoveRow(calculatedIndex, sourceType);
800
        }
801

    
802
        /*
803
         * (non-Javadoc)
804
         * 
805
         * @see com.iver.cit.gvsig.fmap.layers.VectorialAdapter#getRecordset()
806
         */
807
        public SelectableDataSource getRecordset() throws DriverLoadException {
808
                if (isEditing) {
809
                        if (ds == null) {
810
                                String name = LayerFactory.getDataSourceFactory()
811
                                                .addDataSource((ObjectDriver) editingDriver);
812

    
813
                                try {
814
                                        ds = new SelectableDataSource(LayerFactory
815
                                                        .getDataSourceFactory().createRandomDataSource(
816
                                                                        name, DataSourceFactory.MANUAL_OPENING));
817
                                        ds.start();
818
                                        ds.setSelectionSupport(ods.getSelectionSupport());
819

    
820
                                } catch (NoSuchTableException e) {
821
                                        throw new RuntimeException(e);
822
                                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
823
                                        throw new RuntimeException(e);
824
                                }
825
                        }
826

    
827
                        return ds;
828
                } else {
829
                        return ods;
830
                }
831
        }
832

    
833

    
834
        /**
835
         * DOCUMENT ME!
836
         * 
837
         * @return
838
         */
839
        public FBitSet getSelection() {
840
                /*
841
                 * try { return getRecordset().getSelection(); } catch
842
                 * (DriverLoadException e) { // TODO Auto-generated catch block
843
                 * e.printStackTrace(); } return null;
844
                 */
845
                return getRecordset().getSelection();
846
        }
847

    
848
        public void setSelection(FBitSet selection) {
849
                /*
850
                 * try { getRecordset().setSelection(selection); } catch
851
                 * (DriverLoadException e) { // TODO Auto-generated catch block
852
                 * e.printStackTrace(); }
853
                 */
854
                getRecordset().setSelection(selection);
855
        }
856

    
857
        /**
858
         * DOCUMENT ME!
859
         * 
860
         * @return DOCUMENT ME!
861
         */
862
        public boolean isEditing() {
863
                return isEditing;
864
        }
865

    
866
        public int getInversedIndex(long rowIndex) {
867
                int intervalNotDeleted = 0;
868
                int antDeleted = -1;
869
                int idPedido = (int) rowIndex;
870
                int numNotDeleted = 0;
871
                int numBorradosAnt = 0;
872

    
873
                for (int i = delRows.nextSetBit(0); i >= 0; i = delRows
874
                                .nextSetBit(i + 1)) {
875
                        intervalNotDeleted = i - antDeleted - 1;
876
                        numNotDeleted += intervalNotDeleted;
877
                        if (i > idPedido) {
878
                                numNotDeleted = numNotDeleted + (i - idPedido);
879
                                break;
880
                        }
881
                        numBorradosAnt++;
882
                        antDeleted = i;
883
                }
884
                numNotDeleted = idPedido - numBorradosAnt;
885
                // System.out.println("Piden Viejo : "+ rowIndex + " y devuelvo como
886
                // nuevo " + (numNotDeleted));
887
                return numNotDeleted;
888
        }
889

    
890
        /**
891
         * DOCUMENT ME!
892
         * 
893
         * @param rowIndex
894
         *            DOCUMENT ME!
895
         * 
896
         * @return DOCUMENT ME!
897
         */
898
        public int getCalculatedIndex(long rowIndex) {
899
                int numNotDeleted = 0;
900
                int intervalNotDeleted = 0;
901
                int antDeleted = -1;
902
                int calculatedIndex;
903
                int idPedido = (int) rowIndex;
904
                int numBorradosAnt = 0;
905

    
906
                for (int i = delRows.nextSetBit(0); i >= 0; i = delRows
907
                                .nextSetBit(i + 1)) {
908
                        intervalNotDeleted = i - antDeleted - 1;
909
                        numNotDeleted += intervalNotDeleted;
910
                        if (numNotDeleted > idPedido) {
911
                                break;
912
                        }
913
                        numBorradosAnt++;
914
                        antDeleted = i;
915
                }
916
                calculatedIndex = numBorradosAnt + idPedido;
917
                // System.out.println("Piden Registro : "+ rowIndex + " y devuelvo el "
918
                // + (calculatedIndex));
919
                return calculatedIndex;
920
        }
921

    
922
        /**
923
         * DOCUMENT ME!
924
         * 
925
         * @author Vicente Caballero Navarro
926
         */
927
        private class myObjectDriver implements ObjectDriver {
928
                /*
929
                 * (non-Javadoc)
930
                 * 
931
                 * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#getPrimaryKeys()
932
                 */
933
                public int[] getPrimaryKeys() throws DriverException {
934
                        return ods.getPrimaryKeys();
935
                        // int[] pk=new int[1];
936
                        /*
937
                         * for (int i=0;i<getRowCount();i++){ pk[i]=i; }
938
                         */
939
                        // pk[0]=1;
940
                        // return pk;
941
                }
942

    
943
                /*
944
                 * (non-Javadoc)
945
                 * 
946
                 * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#write(com.hardcode.gdbms.engine.data.edition.DataWare)
947
                 */
948
                public void write(DataWare dataWare) throws DriverException {
949
                        DataWare dataWareOrig = ods
950
                                        .getDataWare(DataSourceFactory.DATA_WARE_DIRECT_MODE);
951
                        dataWareOrig.commitTrans();
952
                }
953

    
954
                /*
955
                 * (non-Javadoc)
956
                 * 
957
                 * @see com.hardcode.gdbms.engine.data.driver.GDBMSDriver#setDataSourceFactory(com.hardcode.gdbms.engine.data.DataSourceFactory)
958
                 */
959
                public void setDataSourceFactory(DataSourceFactory dsf) {
960
                        ods.setDataSourceFactory(dsf);
961
                }
962

    
963
                /*
964
                 * (non-Javadoc)
965
                 * 
966
                 * @see com.hardcode.driverManager.Driver#getName()
967
                 */
968
                public String getName() {
969
                        return ods.getName();
970
                }
971

    
972
                /*
973
                 * (non-Javadoc)
974
                 * 
975
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldValue(long,
976
                 *      int)
977
                 */
978
                public Value getFieldValue(long rowIndex, int fieldId)
979
                                throws DriverException {
980
                        // Si no est? en el fichero de expansi?n
981
                        // Integer integer = new Integer(getCalculatedIndex(rowIndex));
982

    
983

    
984
                        try {
985
                                IRow row = getRow((int)rowIndex);
986
                                return row.getAttribute(fieldId);
987
//                                if (!relations.containsKey(integer)) {
988
//                                        return ods.getFieldValue(rowIndex, fieldId);
989
//                                } else {
990
//                                        int num = ((Integer) relations.get(integer)).intValue();
991
//                                        DefaultRowEdited feat = (DefaultRowEdited) expansionFile
992
//                                                        .getRow(num);
993
//
994
//                                        if (feat == null) {
995
//                                                return null;
996
//                                        }
997
//
998
//                                        return feat.getAttribute(fieldId);
999
//                                }
1000
//                        } catch (DriverException e) {
1001
//                                e.printStackTrace();
1002
//                                throw new DriverException(e);
1003
                        } catch (IOException e) {
1004
                                e.printStackTrace();
1005
                                throw new DriverException(e);
1006
                        } catch (DriverIOException e) {
1007
                                e.printStackTrace();
1008
                                throw new DriverException(e);
1009
                        }
1010

    
1011
                        /**
1012
                         * try { if (!relations.containsKey(integer)) { // Si ha sido
1013
                         * eliminada if (delRows.get(integer.intValue())) { return null; }
1014
                         * else { return ods.getFieldValue(rowIndex, fieldId); }} else { int
1015
                         * num = ((Integer) relations.get(integer)).intValue();
1016
                         * DefaultRowEdited feat = (DefaultRowEdited)
1017
                         * expansionFile.getRow(num); if (feat==null)return null; return
1018
                         * feat.getAttribute(fieldId); }} catch (DriverException e) {
1019
                         * e.printStackTrace(); throw new DriverException(e); } catch
1020
                         * (IOException e) { e.printStackTrace(); throw new
1021
                         * DriverException(e); }
1022
                         */
1023
                }
1024

    
1025
                /*
1026
                 * (non-Javadoc)
1027
                 * 
1028
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldCount()
1029
                 */
1030
                public int getFieldCount() throws DriverException {
1031
                        return fastAccessFields.size();
1032
                }
1033

    
1034
                /*
1035
                 * (non-Javadoc)
1036
                 * 
1037
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldName(int)
1038
                 */
1039
                public String getFieldName(int fieldId) throws DriverException {
1040
//                        int i=0;
1041
//                        for (Iterator iter = actualFields.values().iterator(); iter.hasNext();) {
1042
//                                InternalField fld = (InternalField) iter.next();
1043
//                                if (i == fieldId)
1044
//                                        return fld.getFieldDesc().getFieldAlias();
1045
//                                i++;
1046
//                                
1047
//                        }
1048
//                        throw new DriverException("FieldId " + fieldId + " not found ");
1049
                        FieldDescription aux = (FieldDescription) fastAccessFields.get(fieldId);
1050
                        return aux.getFieldAlias();
1051
                        // return null;
1052
                        // return ods.getFieldName(fieldId);
1053
                }
1054

    
1055
                /*
1056
                 * (non-Javadoc)
1057
                 * 
1058
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getRowCount()
1059
                 */
1060
                public long getRowCount() {
1061
                        try {
1062
                                return (int) (ods.getRowCount() + numAdd)
1063
                                                - delRows.cardinality();// -
1064
                                // expansionFile.getInvalidRows().cardinality();
1065
                        } catch (DriverException e) {
1066
                                // TODO Auto-generated catch block
1067
                                e.printStackTrace();
1068
                        }
1069

    
1070
                        return 0;
1071
                }
1072

    
1073
                /*
1074
                 * (non-Javadoc)
1075
                 * 
1076
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldType(int)
1077
                 */
1078
                public int getFieldType(int fieldId) throws DriverException {
1079
//                        int i=0;
1080
//                        for (Iterator iter = actualFields.values().iterator(); iter.hasNext();) {
1081
//                                InternalField fld = (InternalField) iter.next();
1082
//                                if (i == fieldId)
1083
//                                        return fld.getFieldDesc().getFieldType();
1084
//                                i++;
1085
//                                
1086
//                        }
1087
                        FieldDescription aux = (FieldDescription) fastAccessFields.get(fieldId);
1088
                        return aux.getFieldType();
1089
                        
1090
//                        return ods.getFieldType(i);
1091
                }
1092

    
1093
                public int getFieldWidth(int fieldId) throws DriverException {
1094
//                        int i=0;
1095
//                        for (Iterator iter = actualFields.values().iterator(); iter.hasNext();) {                                
1096
//                                InternalField fld = (InternalField) iter.next();
1097
////                                if (fld.getFieldIndex() == i)
1098
////                                        return fld.getFieldDesc().getFieldLength();
1099
//                                if (i == fieldId)
1100
//                                        return fld.getFieldDesc().getFieldLength();
1101
//                                i++;
1102
//                                
1103
//                        }
1104
//
1105
//                        return ods.getFieldWidth(i);
1106
                        FieldDescription aux = (FieldDescription) fastAccessFields.get(fieldId);
1107
                        return aux.getFieldLength();
1108

    
1109
                }
1110

    
1111
                public void reload() throws IOException, DriverException {
1112
                        ods.reload();
1113
                        
1114
                }
1115
        }
1116

    
1117
        public CommandRecord getCommandRecord() {
1118
                return cr;
1119
        }
1120

    
1121
        protected void fireAfterRemoveRow(int index, int sourceType) {
1122
                AfterRowEditEvent event = new AfterRowEditEvent(this, index,
1123
                                EditionEvent.CHANGE_TYPE_DELETE, sourceType);
1124
                for (int i = 0; i < editionListeners.size(); i++) {
1125
                        IEditionListener listener = (IEditionListener) editionListeners
1126
                                        .get(i);
1127
                        listener.afterRowEditEvent(event);
1128
                }
1129

    
1130
        }
1131

    
1132
        protected boolean fireBeforeRemoveRow(int index, int sourceType) {
1133
                Cancel cancel = new Cancel();
1134
                BeforeRowEditEvent event = new BeforeRowEditEvent(this, index,
1135
                                EditionEvent.CHANGE_TYPE_DELETE, cancel, sourceType);
1136
                for (int i = 0; i < editionListeners.size(); i++) {
1137
                        IEditionListener listener = (IEditionListener) editionListeners
1138
                                        .get(i);
1139
                        listener.beforeRowEditEvent(null, event);
1140
                        if (cancel.isCanceled())
1141
                                return true;
1142
                }
1143
                return false;
1144
        }
1145

    
1146
        protected void fireAfterRowAdded(int calculatedIndex, int sourceType) {
1147
                AfterRowEditEvent event = new AfterRowEditEvent(this, calculatedIndex,
1148
                                EditionEvent.CHANGE_TYPE_ADD, sourceType);
1149
                for (int i = 0; i < editionListeners.size(); i++) {
1150
                        IEditionListener listener = (IEditionListener) editionListeners
1151
                                        .get(i);
1152
                        listener.afterRowEditEvent(event);
1153
                }
1154
        }
1155

    
1156
        protected void fireAfterFieldAdded(FieldDescription field) {
1157
                AfterFieldEditEvent event = new AfterFieldEditEvent(this,field,
1158
                                EditionEvent.CHANGE_TYPE_ADD);
1159
                for (int i = 0; i < editionListeners.size(); i++) {
1160
                        IEditionListener listener = (IEditionListener) editionListeners
1161
                                        .get(i);
1162
                        listener.afterFieldEditEvent(event);
1163
                }
1164
        }
1165

    
1166
        protected void fireAfterFieldRemoved(FieldDescription field) {
1167
                AfterFieldEditEvent event = new AfterFieldEditEvent(this,field,
1168
                                EditionEvent.CHANGE_TYPE_DELETE);
1169
                for (int i = 0; i < editionListeners.size(); i++) {
1170
                        IEditionListener listener = (IEditionListener) editionListeners
1171
                                        .get(i);
1172
                        listener.afterFieldEditEvent(event);
1173
                }
1174
        }
1175

    
1176
        protected void fireAfterFieldModified(FieldDescription field) {
1177
                AfterFieldEditEvent event = new AfterFieldEditEvent(this,field,
1178
                                EditionEvent.CHANGE_TYPE_MODIFY);
1179
                for (int i = 0; i < editionListeners.size(); i++) {
1180
                        IEditionListener listener = (IEditionListener) editionListeners
1181
                                        .get(i);
1182
                        listener.afterFieldEditEvent(event);
1183
                }
1184
        }
1185
        
1186
        
1187
        protected boolean fireBeforeRowAdded(int sourceType)
1188
                        throws DriverIOException, IOException {
1189
                Cancel cancel = new Cancel();
1190
                BeforeRowEditEvent event = new BeforeRowEditEvent(this, getRowCount(),
1191
                                EditionEvent.CHANGE_TYPE_ADD, cancel, sourceType);
1192
                for (int i = 0; i < editionListeners.size(); i++) {
1193
                        IEditionListener listener = (IEditionListener) editionListeners
1194
                                        .get(i);
1195
                        listener.beforeRowEditEvent(null, event);
1196
                        if (cancel.isCanceled())
1197
                                return true;
1198
                }
1199
                return false;
1200
        }
1201

    
1202
        protected boolean fireBeforeFieldAdded(FieldDescription field)
1203
        throws EditionException {
1204
                Cancel cancel = new Cancel();
1205
                BeforeFieldEditEvent event = new BeforeFieldEditEvent(this, field,
1206
                EditionEvent.CHANGE_TYPE_ADD, cancel);
1207
                for (int i = 0; i < editionListeners.size(); i++) {
1208
                        IEditionListener listener = (IEditionListener) editionListeners
1209
                        .get(i);
1210
                        listener.beforeFieldEditEvent(event);
1211
                        if (cancel.isCanceled())
1212
                                return true;
1213
                }
1214
                return false;
1215
        }
1216

    
1217
        protected boolean fireBeforeRemoveField(FieldDescription field)
1218
        throws EditionException {
1219
                Cancel cancel = new Cancel();
1220
                BeforeFieldEditEvent event = new BeforeFieldEditEvent(this, field,
1221
                EditionEvent.CHANGE_TYPE_DELETE, cancel);
1222
                for (int i = 0; i < editionListeners.size(); i++) {
1223
                        IEditionListener listener = (IEditionListener) editionListeners
1224
                        .get(i);
1225
                        listener.beforeFieldEditEvent(event);
1226
                        if (cancel.isCanceled())
1227
                                return true;
1228
                }
1229
                return false;
1230
        }
1231

    
1232
        
1233
        protected boolean fireBeforeModifyRow(IRow feat, int index, int sourceType) {
1234
                Cancel cancel = new Cancel();
1235
                BeforeRowEditEvent event = new BeforeRowEditEvent(this, index,
1236
                                EditionEvent.CHANGE_TYPE_MODIFY, cancel, sourceType);
1237
                for (int i = 0; i < editionListeners.size(); i++) {
1238
                        IEditionListener listener = (IEditionListener) editionListeners
1239
                                        .get(i);
1240
                        listener.beforeRowEditEvent(feat, event);
1241
                        if (cancel.isCanceled())
1242
                                return true;
1243
                }
1244
                return false;
1245
        }
1246

    
1247
        protected void fireAfterModifyRow(int index, int sourceType) {
1248
                AfterRowEditEvent event = new AfterRowEditEvent(this, index,
1249
                                EditionEvent.CHANGE_TYPE_MODIFY, sourceType);
1250
                for (int i = 0; i < editionListeners.size(); i++) {
1251
                        IEditionListener listener = (IEditionListener) editionListeners
1252
                                        .get(i);
1253
                        listener.afterRowEditEvent(event);
1254
                }
1255

    
1256
        }
1257

    
1258
        protected void fireStartEditionEvent(int sourceType) {
1259
                EditionEvent ev = new EditionEvent(this, EditionEvent.START_EDITION,
1260
                                sourceType);
1261
                for (int i = 0; i < editionListeners.size(); i++) {
1262
                        IEditionListener listener = (IEditionListener) editionListeners
1263
                                        .get(i);
1264
                        listener.processEvent(ev);
1265
                }
1266

    
1267
        }
1268

    
1269
        protected void fireStopEditionEvent(int sourceType) {
1270
                EditionEvent ev = new EditionEvent(this, EditionEvent.STOP_EDITION,
1271
                                sourceType);
1272
                for (int i = 0; i < editionListeners.size(); i++) {
1273
                        IEditionListener listener = (IEditionListener) editionListeners
1274
                                        .get(i);
1275
                        listener.processEvent(ev);
1276
                }
1277

    
1278
        }
1279

    
1280
        protected void fireCancelEditionEvent(int sourceType) {
1281
                EditionEvent ev = new EditionEvent(this, EditionEvent.CANCEL_EDITION,
1282
                                sourceType);
1283
                for (int i = 0; i < editionListeners.size(); i++) {
1284
                        IEditionListener listener = (IEditionListener) editionListeners
1285
                                        .get(i);
1286
                        listener.processEvent(ev);
1287
                }
1288

    
1289
        }
1290

    
1291
        public void addEditionListener(IEditionListener listener) {
1292
                if (!editionListeners.contains(listener))
1293
                        editionListeners.add(listener);
1294
        }
1295

    
1296
        public void removeEditionListener(IEditionListener listener) {
1297
                editionListeners.remove(listener);
1298
        }
1299

    
1300
        public IWriter getWriter() {
1301
                return writer;
1302
        }
1303

    
1304
        protected void setWriter(IWriter writer) {
1305
                this.writer = writer;
1306

    
1307
        }
1308

    
1309
        public ITableDefinition getTableDefinition() throws DriverLoadException,
1310
                        DriverException {
1311
                TableDefinition tableDef = new TableDefinition();
1312
                tableDef.setFieldsDesc(getRecordset().getFieldsDescription());
1313
                tableDef.setName(getRecordset().getSourceInfo().name);
1314
                return tableDef;
1315
        }
1316

    
1317
        public void validateRow(IRow row) throws EditionException {
1318
                for (int i = 0; i < rules.size(); i++) {
1319
                        IRule rule = (IRule) rules.get(i);
1320
                        boolean bAux = rule.validate(row);
1321
                        if (bAux == false) {
1322
                                EditionException ex = new EditionException(
1323
                                                "NOT follow the rule: " + rule.getDescription());
1324
                                // TODO: Lanzar una RuleException con datos como el registro
1325
                                // que no cumple, la regla que no lo ha cumplido, etc.
1326
                                throw ex;
1327
                        }
1328
                }
1329
        }
1330

    
1331
        public ArrayList getRules() {
1332
                return rules;
1333
        }
1334

    
1335
        public void setRules(ArrayList rules) {
1336
                this.rules = rules;
1337
        }
1338

    
1339
        private void clean() throws IOException, DriverException {
1340
                expansionFile.close();
1341
                relations.clear();
1342
                numAdd = 0;
1343
                delRows.clear();
1344
                // TODO: Es muy probable que necesitemos un reload de los datasources, al
1345
                // igual que lo tenemos en las capas. Por ahora, basta con retocar
1346
                // listInternalFields, pero casi seguro que lo correcto ser?a hacer un
1347
                // reload completo.
1348
                initalizeFields(ods);
1349
                
1350
//                listInternalFields.clear();
1351
//                listInternalFields.add(actualFields);
1352
        }
1353

    
1354
        /*
1355
         * (non-Javadoc)
1356
         * 
1357
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#getFieldManager()
1358
         */
1359
        public IFieldManager getFieldManager() {
1360
                if (ods.getDriver() instanceof IWriteable)
1361
                {
1362
                        IWriter writer = ((IWriteable)ods.getDriver()).getWriter();
1363
                        if ((writer != null) && (writer instanceof IFieldManager))
1364
                        {
1365
                                return (IFieldManager) writer;
1366
                        }
1367
                }
1368
                return null;
1369
        }
1370

    
1371
        /**
1372
         * Tiene en cuenta los campos actuales para formatear una row con ellos. Le
1373
         * pasamos los campos que hab?a en el momento en que se cre? esa row.
1374
         * 
1375
         * @param edRow
1376
         * @param indexInternalFields
1377
         * @return
1378
         */
1379
        public IRowEdited createExternalRow(IRowEdited edRow,
1380
                        int indexInternalFields) {
1381
                
1382
                // para acelerar
1383
                if (bFieldsHasBeenChanged == false)
1384
                        return edRow;
1385
                
1386
                Value[] att = edRow.getAttributes();
1387
                TreeMap ancientFields = (TreeMap) listInternalFields
1388
                                .get(indexInternalFields);
1389
                Value[] newAtt = new Value[actualFields.size()];
1390
                Collection aux = actualFields.values();
1391
                Iterator it = aux.iterator();
1392
                int i = 0;
1393
                Value val = null;
1394
                while (it.hasNext()) {
1395
                        // Para cada campo de los actuales, miramos si ya estaba cuando
1396
                        // el registro estaba guardado. 
1397
                        // Si estaba, cogemos el valor de ese campo en el registro
1398
                        // guardado. Si no estaba, ha sido a?adido despu?s y ponemos
1399
                        // su valor por defecto.
1400
                        // Nota importante: fieldIndex es el ?ndice del campo cuando
1401
                        // se guard?. NO es el ?ndice actual dentro de actualFields.
1402
                        // Se usa SOLO para recuperar el valor de los atributos
1403
                        // antiguos. Por eso no nos preocupamos de mantener actuallizados
1404
                        // el resto de campos cuando se borra o a?ade un nuevo campo.
1405
                        InternalField fld = (InternalField) it.next();
1406
                        // System.err.println("fld = " + fld.getFieldDesc().getFieldAlias() +  " id=" + fld.getFieldId());
1407
                        if (ancientFields.containsKey(fld.getFieldId())) {
1408
                                InternalField ancientField = (InternalField) ancientFields
1409
                                                .get(fld.getFieldId());
1410
                                // val = att[ancientField.getFieldIndex()];
1411
                                val = att[ancientField.getFieldId().intValue()];
1412
                                // System.out.println("fld: " + fld.getFieldDesc().getFieldAlias() + " ancient:" + " val" + val);
1413
                        } else
1414
                                val = fld.getFieldDesc().getDefaultValue();
1415
                        newAtt[i++] = val;
1416
                }
1417
                IRowEdited newRow = (IRowEdited) edRow.cloneRow();
1418
                newRow.setAttributes(newAtt);
1419
                return newRow;
1420
        }
1421

    
1422
        public void removeField(String fieldName) throws EditionException {
1423

    
1424
                InternalField fld = findFieldByName(fieldName);
1425
                if (fld == null)
1426
                        throw new EditionException("Field " + fieldName + " not found when removing field");
1427
                Command command = new RemoveFieldCommand(this, fld);
1428
                if (complex) {
1429
                        commands.add(command);
1430
                } else {
1431
                        cr.pushCommand(command);
1432
                }
1433
                doRemoveField(fld);
1434

    
1435
        }
1436

    
1437
        private InternalField findFieldByName(String fieldName) {
1438
                Collection aux = actualFields.values();
1439
                Iterator it = aux.iterator();
1440
                while (it.hasNext()) {
1441
                        InternalField fld = (InternalField) it.next();
1442
                        if (fld.getFieldDesc().getFieldAlias().compareToIgnoreCase(fieldName) == 0)
1443
                                return fld;
1444
                }
1445
                
1446
                return null;
1447
        }
1448

    
1449
        public void undoRemoveField(InternalField field) throws EditionException {
1450
                // field.setDeleted(false);
1451
//                field.setFieldIndex(actualFields.size());
1452
                actualFields.put(field.getFieldId(), field);
1453
                fieldsChanged();
1454
                fireAfterFieldAdded(field.getFieldDesc());
1455
        }
1456

    
1457
        public void doRemoveField(InternalField field) throws EditionException {
1458
                boolean cancel = fireBeforeRemoveField(field.getFieldDesc());
1459
                if (cancel) return;
1460
                actualFields.remove(field.getFieldId());
1461
                fieldsChanged();
1462
                fireAfterFieldRemoved(field.getFieldDesc());
1463
        }
1464

    
1465
        public void renameField(String antName, String newName) throws EditionException {
1466

    
1467
                InternalField fld = findFieldByName(antName);
1468
                Command command = new RenameFieldCommand(this, fld, newName);
1469
                if (complex) {
1470
                        commands.add(command);
1471
                } else {
1472
                        cr.pushCommand(command);
1473
                }
1474
                doRenameField(fld, newName);
1475

    
1476
        }
1477
        
1478
        public void undoRenameField(InternalField field, String antName) throws EditionException  {
1479
                fieldsChanged();
1480
                fireAfterFieldModified(field.getFieldDesc());
1481

    
1482
        }
1483

    
1484
        public void doRenameField(InternalField field, String newName) throws EditionException  {
1485
                fieldsChanged();
1486
                fireAfterFieldModified(field.getFieldDesc());
1487

    
1488
        }
1489

    
1490

    
1491
        public void addField(FieldDescription field) throws EditionException {
1492

    
1493
                InternalField fld = new InternalField(field, InternalField.ADDED, new Integer(listFields.size()));
1494
                Command command = new AddFieldCommand(this, fld);
1495
                if (complex) {
1496
                        commands.add(command);
1497
                } else {
1498
                        cr.pushCommand(command);
1499
                }
1500
                listFields.add(fld);
1501
                doAddField(fld);
1502

    
1503
        }
1504

    
1505
        public void undoAddField(InternalField field) throws EditionException {
1506
                boolean cancel = fireBeforeRemoveField(field.getFieldDesc());
1507
                if (cancel)
1508
                        return;
1509

    
1510
                // field.setDeleted(true);
1511
                actualFields.remove(field.getFieldId());
1512
                fieldsChanged();
1513
                fireAfterFieldRemoved(field.getFieldDesc());
1514
                
1515
        }
1516

    
1517
        public int doAddField(InternalField field) throws EditionException {
1518
                boolean cancel;
1519
                cancel = fireBeforeFieldAdded(field.getFieldDesc());
1520
                if (cancel)
1521
                        return -1;
1522

    
1523
                // field.setDeleted(false);
1524
//                field.setFieldIndex(actualFields.size());
1525
                actualFields.put(field.getFieldId(), field);
1526
                fieldsChanged();
1527
                fireAfterFieldAdded(field.getFieldDesc());
1528
//                return field.getFieldIndex();
1529
                return field.getFieldId().intValue();
1530
        }
1531
        
1532
        public Driver getOriginalDriver()
1533
        {
1534
                return ods.getDriver();
1535
        }
1536
        
1537
        /**
1538
         * Use it to be sure the recordset will have the right fields. It forces a new SelectableDataSource
1539
         * to be created next time it is needed
1540
         */
1541
        public void cleanSelectableDatasource() {
1542
                ds = null;
1543
        }
1544

    
1545
        
1546
//        private InternalField getInternalFieldByIndex(int fieldId)
1547
//        {
1548
//                for (Iterator iter = actualFields.values().iterator(); iter.hasNext();) {
1549
//                        InternalField fld = (InternalField) iter.next();
1550
//                        if (fld.getFieldIndex() == fieldId)
1551
//                                return fld;
1552
//                }
1553
//                return null;
1554
//        }
1555
        
1556
}